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

@Injectable({
  providedIn: 'root',
})
export class MemberCasinoMoneyMockApi {
  private _casinoMoneys: any[] = casinoMoneysData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ CasinoMoneys - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/member/casino-money/casino-moneys', 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 casinoMoneys
        let casinoMoneys: any[] | null = cloneDeep(this._casinoMoneys);

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

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

        // Paginate - Start
        const casinoMoneysLength = casinoMoneys.length;

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

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

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

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

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

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

        // Clone the casinoMoneys
        const casinoMoneys = cloneDeep(this._casinoMoneys);

        // Find the casinoMoney
        const casinoMoney = casinoMoneys.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ CasinoMoney - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/casino-money/casino-money')
      .reply(() => {
        // Generate a new casinoMoney
        const newCasinoMoney = {
          id: FuseMockApiUtils.guid(),
          signinId: '',
          nickname: '',
          highRank: '',
          rank: '',
          level: '',
          accountHolder: '',
          phoneNumber: '',
          ownCash: 0,
          ownComp: 0,
          ownCoupon: 0,
          gameMoney: 0,
          todayComp: 0,
          totalDeposit: 0,
          totalWithdraw: 0,
          balance: 0,
        };

        // Unshift the new casinoMoney
        this._casinoMoneys.unshift(newCasinoMoney);

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

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

        // Prepare the updated casinoMoney
        let updatedCasinoMoney = null;

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

            // Store the updated casinoMoney
            updatedCasinoMoney = casinoMoneys[index];
          }
        });

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

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

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

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