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

@Injectable({
  providedIn: 'root',
})
export class BankDepositMockApi {
  private _deposits: any[] = depositsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Deposits - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/bank/deposit/deposits', 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 deposits
        let deposits: any[] | null = cloneDeep(this._deposits);

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

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

        // Paginate - Start
        const depositsLength = deposits.length;

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

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

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

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

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

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

        // Clone the deposits
        const deposits = cloneDeep(this._deposits);

        // Find the deposit
        const deposit = deposits.find((item: any) => item.id === id);

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

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

        // Unshift the new deposit
        this._deposits.unshift(newDeposit);

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

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

        // Prepare the updated deposit
        let updatedDeposit = null;

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

            // Store the updated deposit
            updatedDeposit = deposits[index];
          }
        });

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

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

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

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