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

@Injectable({
  providedIn: 'root',
})
export class ReportMoneyLogMockApi {
  private _moneyLogs: any[] = moneyLogsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ MoneyLogs - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/money-log/money-logs', 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 moneyLogs
        let moneyLogs: any[] | null = cloneDeep(this._moneyLogs);

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

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

        // Paginate - Start
        const moneyLogsLength = moneyLogs.length;

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

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

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

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

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

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

        // Clone the moneyLogs
        const moneyLogs = cloneDeep(this._moneyLogs);

        // Find the moneyLog
        const moneyLog = moneyLogs.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ MoneyLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/money-log/money-log')
      .reply(() => {
        // Generate a new moneyLog
        const newMoneyLog = {
          id: FuseMockApiUtils.guid(),
          category: '',
          name: 'A New User',
          description: '',
          tags: [],
          sku: '',
          barcode: '',
          brand: '',
          vendor: '',
          stock: '',
          reserved: '',
          cost: '',
          basePrice: '',
          taxPercent: '',
          price: '',
          weight: '',
          thumbnail: '',
          images: [],
          active: false,
        };

        // Unshift the new moneyLog
        this._moneyLogs.unshift(newMoneyLog);

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

    // -----------------------------------------------------------------------------------------------------
    // @ MoneyLog - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/report/money-log/money-log')
      .reply(({ request }) => {
        // Get the id and moneyLog
        const id = request.body.id;
        const moneyLog = cloneDeep(request.body.moneyLog);

        // Prepare the updated moneyLog
        let updatedMoneyLog = null;

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

            // Store the updated moneyLog
            updatedMoneyLog = moneyLogs[index];
          }
        });

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

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

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

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