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

@Injectable({
  providedIn: 'root',
})
export class BoardCustomerTemplateMockApi {
  private _customerTemplates: any[] = customerTemplatesData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ CustomerTemplates - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/board/customer-template/customer-templates', 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 customerTemplates
        let customerTemplates: any[] | null = cloneDeep(
          this._customerTemplates
        );

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

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

        // Paginate - Start
        const customerTemplatesLength = customerTemplates.length;

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

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

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

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

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

    // -----------------------------------------------------------------------------------------------------
    // @ CustomerTemplate - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/board/customer-template/customer-template')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the customerTemplates
        const customerTemplates = cloneDeep(this._customerTemplates);

        // Find the customerTemplate
        const customerTemplate = customerTemplates.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ CustomerTemplate - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/board/customer-template/customer-template')
      .reply(() => {
        // Generate a new customerTemplate
        const newCustomerTemplate = {
          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 customerTemplate
        this._customerTemplates.unshift(newCustomerTemplate);

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

    // -----------------------------------------------------------------------------------------------------
    // @ CustomerTemplate - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/board/customer-template/customer-template')
      .reply(({ request }) => {
        // Get the id and customerTemplate
        const id = request.body.id;
        const customerTemplate = cloneDeep(request.body.customerTemplate);

        // Prepare the updated customerTemplate
        let updatedCustomerTemplate = null;

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

            // Store the updated CustomerTemplate
            updatedCustomerTemplate = customerTemplates[index];
          }
        });

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

    // -----------------------------------------------------------------------------------------------------
    // @ CustomerTemplate - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/board/customer-template/customer-template')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

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

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