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

@Injectable({
  providedIn: 'root',
})
export class GameCasinoMockApi {
  private _casinos: any[] = casinosData;

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

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

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

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

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

        // Paginate - Start
        const casinosLength = casinos.length;

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

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

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

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

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

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

        // Clone the casinos
        const casinos = cloneDeep(this._casinos);

        // Find the casino
        const casino = casinos.find((item: any) => item.id === id);

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

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

      // Unshift the new casino
      this._casinos.unshift(newCasino);

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

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

        // Prepare the updated casino
        let updatedCasino = null;

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

            // Store the updated casino
            updatedCasino = casinos[index];
          }
        });

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

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

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

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