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

@Injectable({
  providedIn: 'root',
})
export class ReportCompLogMockApi {
  private _compLogs: any[] = compLogsData;

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

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

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

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

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

        // Paginate - Start
        const compLogsLength = compLogs.length;

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

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

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

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

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

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

        // Clone the compLogs
        const compLogs = cloneDeep(this._compLogs);

        // Find the compLog
        const compLog = compLogs.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ CompLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/comp-log/comp-log')
      .reply(() => {
        // Generate a new compLog
        const newCompLog = {
          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 compLog
        this._compLogs.unshift(newCompLog);

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

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

        // Prepare the updated compLog
        let updatedCompLog = null;

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

            // Store the updated compLog
            updatedCompLog = compLogs[index];
          }
        });

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

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

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

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