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

@Injectable({
  providedIn: 'root',
})
export class BankWithdrawMockApi {
  private _withdraws: any[] = withdrawsData;

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

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

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

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

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

        // Paginate - Start
        const withdrawsLength = withdraws.length;

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

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

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

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

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

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

        // Clone the users
        const withdraws = cloneDeep(this._withdraws);

        // Find the withdraw
        const withdraw = withdraws.find((item: any) => item.id === id);

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

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

        // Unshift the new withdraw
        this._withdraws.unshift(newWithdraw);

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

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

        // Prepare the updated withdraw
        let updatedWithdraw = null;

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

            // Store the updated withdraw
            updatedWithdraw = withdraws[index];
          }
        });

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

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

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

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