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

@Injectable({
  providedIn: 'root',
})
export class BankPartnerCalculateMockApi {
  private _partnerCalculates: any[] = partnerCalculatesData;

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

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

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

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

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

        // Paginate - Start
        const partnerCalculatesLength = partnerCalculates.length;

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

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

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

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

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

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

        // Clone the partnerCalculates
        const partnerCalculates = cloneDeep(this._partnerCalculates);

        // Find the partnerCalculate
        const partnerCalculate = partnerCalculates.find(
          (item: any) => item.id === id
        );

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

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

        // Unshift the new partnerCalculate
        this._partnerCalculates.unshift(newPartnerCalculate);

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

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

        // Prepare the updated partnerCalculate
        let updatedPartnerCalculate = null;

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

            // Store the updated partnerCalculate
            updatedPartnerCalculate = partnerCalculates[index];
          }
        });

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

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

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

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