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

@Injectable({
  providedIn: 'root',
})
export class GameSlotMockApi {
  private _slots: any[] = slotsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Slots - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/game/slot/slots', 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 slots
        let slots: any[] | null = cloneDeep(this._slots);

        // Sort the slots
        if (sort === 'signinId' || sort === 'nickname' || sort === 'gameId') {
          slots.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 {
          slots.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const slotsLength = slots.length;

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

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

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

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

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

    // -----------------------------------------------------------------------------------------------------
    // @ Slot - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/game/slot/slot')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the slots
        const slots = cloneDeep(this._slots);

        // Find the slot
        const slot = slots.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Slot - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService.onPost('api/apps/gmae/slot/slot').reply(() => {
      // Generate a new slot
      const newSlot = {
        id: FuseMockApiUtils.guid(),
        startDate: '',
        finishDate: '',
        totalBetting: '',
        winningMoney: '',
        proceedingMoney: '',
        calculate: '',
        index: '',
        division: '',
        rank: '',
        nickname: '',
        bettingProgress: '',
        odds: '',
        bettingMoney: '',
        hitMoney: '',
        bettingTime: '',
        result: '',
        delete: '',
      };

      // Unshift the new slot
      this._slots.unshift(newSlot);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Slot - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/game/slot/slot')
      .reply(({ request }) => {
        // Get the id and slot
        const id = request.body.id;
        const slot = cloneDeep(request.body.slot);

        // Prepare the updated slot
        let updatedSlot = null;

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

            // Store the updated slot
            updatedSlot = slots[index];
          }
        });

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

    // -----------------------------------------------------------------------------------------------------
    // @ Slot - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/game/slot/slot')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

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

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