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

@Injectable({
  providedIn: 'root',
})
export class ReportModificationLogMockApi {
  private _modificationLogs: any[] = modificationLogsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ ModificationLogs - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/modification-log/modification-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 modificationLogs
        let modificationLogs: any[] | null = cloneDeep(this._modificationLogs);

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

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

        // Paginate - Start
        const modificationLogsLength = modificationLogs.length;

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

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

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

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

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

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

        // Clone the modificationLogs
        const modificationLogs = cloneDeep(this._modificationLogs);

        // Find the modificationLog
        const modificationLog = modificationLogs.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ ModificationLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/modification-log/modification-log')
      .reply(() => {
        // Generate a new modificationLog
        const newModificationLog = {
          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 modificationLog
        this._modificationLogs.unshift(newModificationLog);

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

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

        // Prepare the updated modificationLog
        let updatedModificationLog = null;

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

            // Store the updated modificationLog
            updatedModificationLog = modificationLogs[index];
          }
        });

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

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

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

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