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

@Injectable({
  providedIn: 'root',
})
export class ReportMonthlyMockApi {
  private _monthlys: any[] = monthlysData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Monthlys - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/monthly/monthlys', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'day';
        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 monthlys
        let monthlys: any[] | null = cloneDeep(this._monthlys);

        // Sort the monthlys
        if (
          sort === 'day' ||
          sort === 'monthlyDiposit' ||
          sort === 'monthlyWithdraw'
        ) {
          monthlys.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 {
          monthlys.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const monthlysLength = monthlys.length;

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

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

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

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

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

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

        // Clone the monthlys
        const monthlys = cloneDeep(this._monthlys);

        // Find the monthly
        const monthly = monthlys.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Monthly - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/monthly/monthly')
      .reply(() => {
        // Generate a new monthly
        const newMonthly = {
          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 monthly
        this._monthlys.unshift(newMonthly);

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

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

        // Prepare the updated monthly
        let updatedMonthly = null;

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

            // Store the updated monthly
            updatedMonthly = monthlys[index];
          }
        });

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

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

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

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