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

@Injectable({
  providedIn: 'root',
})
export class ReportDailyMockApi {
  private _dailys: any[] = dailysData;

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

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

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

        // Sort the dailys
        if (
          sort === 'lastDayHoldingMoney' ||
          sort === 'memberCharge' ||
          sort === 'memberExchange'
        ) {
          dailys.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 {
          dailys.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const dailysLength = dailys.length;

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

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

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

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

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

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

        // Clone the dailys
        const dailys = cloneDeep(this._dailys);

        // Find the daily
        const daily = dailys.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Daily - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService.onPost('api/apps/report/daily/daily').reply(() => {
      // Generate a new daily
      const newDaily = {
        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 daily
      this._dailys.unshift(newDaily);

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

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

        // Prepare the updated daily
        let updatedDaily = null;

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

            // Store the updated daily
            updatedDaily = dailys[index];
          }
        });

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

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

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

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