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

@Injectable({
  providedIn: 'root',
})
export class BankWebCalculateMockApi {
  private _webCalculates: any[] = webCalculatesData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ WebCalculates - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/bank/web-calculate/web-calculates', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'webDepositId';
        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 webCalculates
        let webCalculates: any[] | null = cloneDeep(this._webCalculates);

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

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

        // Paginate - Start
        const webCalculatesLength = webCalculates.length;

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

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

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

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

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

    // -----------------------------------------------------------------------------------------------------
    // @ WebCalculate - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/bank/web-calculate/web-calculate')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the webCalculates
        const webCalculates = cloneDeep(this._webCalculates);

        // Find the webCalculate
        const webCalculate = webCalculates.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ WebCalculate - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/bank/web-calculate/web-calculate')
      .reply(() => {
        // Generate a new webCalculate
        const newWebCalculate = {
          id: FuseMockApiUtils.guid(),
          rank: '',
          level: '',
          nickname: '',
          paymentDue: '',
          calculateType: '',
          accountHolder: '',
          note: '',
          registrationDate: '',
          processDate: '',
          deposit: '',
          withdrawal: '',
          total: '',
          gameMoney: '',
          highRank: '',
          state: '',
        };

        // Unshift the new webCalculate
        this._webCalculates.unshift(newWebCalculate);

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

    // -----------------------------------------------------------------------------------------------------
    // @ WebCalculate - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/bank/web-calculate/web-calculate')
      .reply(({ request }) => {
        // Get the id and webCalculate
        const id = request.body.id;
        const webCalculate = cloneDeep(request.body.webCalculate);

        // Prepare the updated webCalculate
        let updatedWebCalculate = null;

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

            // Store the updated webCalculate
            updatedWebCalculate = webCalculates[index];
          }
        });

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

    // -----------------------------------------------------------------------------------------------------
    // @ WebCalculate - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/bank/web-calculate/web-calculate')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

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

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