import { Injectable } from '@angular/core';
import { assign, cloneDeep } from 'lodash-es';
import { FuseMockApiService, FuseMockApiUtils } from '@fuse/lib/mock-api';
import { todayBets as todayBetsData } from './data';

@Injectable({
  providedIn: 'root',
})
export class ReportTodayBetMockApi {
  private _todayBets: any[] = todayBetsData;

  /**
   * Constructor
   */
  constructor(private _fuseMockApiService: FuseMockApiService) {
    // Register Mock API handlers
    this.registerHandlers();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ TodayBets - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/today-bet/today-bets', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'signinId';
        const order = request.params.get('order') || 'asc';
        const page = parseInt(request.params.get('page') ?? '1', 10);
        const size = parseInt(request.params.get('size') ?? '10', 10);

        // Clone the todayBets
        let todayBets: any[] | null = cloneDeep(this._todayBets);

        // Sort the todayBets
        if (sort === 'signinId' || sort === 'nickname' || sort === 'rank') {
          todayBets.sort((a, b) => {
            const fieldA = a[sort].toString().toUpperCase();
            const fieldB = b[sort].toString().toUpperCase();
            return order === 'asc'
              ? fieldA.localeCompare(fieldB)
              : fieldB.localeCompare(fieldA);
          });
        } else {
          todayBets.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

        // If search exists...
        if (search) {
          // Filter the todayBets
          todayBets = todayBets.filter(
            (contact: any) =>
              contact.name &&
              contact.name.toLowerCase().includes(search.toLowerCase())
          );
        }

        // Paginate - Start
        const todayBetsLength = todayBets.length;

        // Calculate pagination details
        const begin = page * size;
        const end = Math.min(size * (page + 1), todayBetsLength);
        const lastPage = Math.max(Math.ceil(todayBetsLength / size), 1);

        // Prepare the pagination object
        let pagination = {};

        // If the requested page number is bigger than
        // the last possible page number, return null for
        // todayBets but also send the last possible page so
        // the app can navigate to there
        if (page > lastPage) {
          todayBets = null;
          pagination = {
            lastPage,
          };
        } else {
          // Paginate the results by size
          todayBets = todayBets.slice(begin, end);

          // Prepare the pagination mock-api
          pagination = {
            length: todayBetsLength,
            size: size,
            page: page,
            lastPage: lastPage,
            startIndex: begin,
            endIndex: end - 1,
          };
        }

        // Return the response
        return [
          200,
          {
            todayBets,
            pagination,
          },
        ];
      });

    // -----------------------------------------------------------------------------------------------------
    // @ TodayBet - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/today-bet/today-bet')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the todayBets
        const todayBets = cloneDeep(this._todayBets);

        // Find the todayBet
        const todayBet = todayBets.find((item: any) => item.id === id);

        // Return the response
        return [200, todayBet];
      });

    // -----------------------------------------------------------------------------------------------------
    // @ TodayBet - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/today-bet/today-bet')
      .reply(() => {
        // Generate a new todayBet
        const newTodayBet = {
          id: FuseMockApiUtils.guid(),
          category: '',
          name: 'A New User',
          description: '',
          tags: [],
          sku: '',
          barcode: '',
          brand: '',
          vendor: '',
          stock: '',
          reserved: '',
          cost: '',
          basePrice: '',
          taxPercent: '',
          price: '',
          weight: '',
          thumbnail: '',
          images: [],
          active: false,
        };

        // Unshift the new todayBet
        this._todayBets.unshift(newTodayBet);

        // Return the response
        return [200, newTodayBet];
      });

    // -----------------------------------------------------------------------------------------------------
    // @ TodayBet - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/report/today-bet/today-bet')
      .reply(({ request }) => {
        // Get the id and todayBet
        const id = request.body.id;
        const todayBet = cloneDeep(request.body.todayBet);

        // Prepare the updated todayBet
        let updatedTodayBet = null;

        // Find the todayBet and update it
        this._todayBets.forEach((item, index, todayBets) => {
          if (item.id === id) {
            // Update the todayBet
            todayBets[index] = assign({}, todayBets[index], todayBet);

            // Store the updated todayBet
            updatedTodayBet = todayBets[index];
          }
        });

        // Return the response
        return [200, updatedTodayBet];
      });

    // -----------------------------------------------------------------------------------------------------
    // @ TodayBet - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/report/today-bet/today-bet')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

        // Find the todayBet and delete it
        this._todayBets.forEach((item, index) => {
          if (item.id === id) {
            this._todayBets.splice(index, 1);
          }
        });

        // Return the response
        return [200, true];
      });
  }
}
