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

@Injectable({
  providedIn: 'root',
})
export class ReportExcelLogMockApi {
  private _excelLogs: any[] = excelLogsData;

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

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

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

        // Sort the excelLogs
        // if (sort === 'sku' || sort === 'name' || sort === 'active') {
        //   excelLogs.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 {
        //   excelLogs.sort((a, b) =>
        //     order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
        //   );
        // }

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

        // Paginate - Start
        const excelLogsLength = excelLogs.length;

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

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

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

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

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

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

        // Clone the excelLogs
        const excelLogs = cloneDeep(this._excelLogs);

        // Find the excelLog
        const excelLog = excelLogs.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ ExcelLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/excel-log/excel-log')
      .reply(() => {
        // Generate a new excelLog
        const newExcelLog = {
          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 excelLog
        this._excelLogs.unshift(newExcelLog);

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

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

        // Prepare the updated excelLog
        let updatedExcelLog = null;

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

            // Store the updated excelLog
            updatedExcelLog = excelLogs[index];
          }
        });

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

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

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

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