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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerOfficeMockApi {
  private _partnerOffices: any[] = partnerOfficesData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ PartnerOffices - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/member/partner-office/partner-offices', 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 partnerOffices
        let partnerOffices: any[] | null = cloneDeep(this._partnerOffices);

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

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

        // Paginate - Start
        const partnerOfficesLength = partnerOffices.length;

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

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

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

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

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerOffice - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/member/partne-office/partner-office')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the partnerOffices
        const partnerOffices = cloneDeep(this._partnerOffices);

        // Find the partnerOffice
        const partnerOffice = partnerOffices.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerOffice - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner-office/partner-office')
      .reply(() => {
        // Generate a new partnerOffice
        const newPartnerOffice = {
          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 partnerOffice
        this._partnerOffices.unshift(newPartnerOffice);

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerOffice - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/member/partner-office/partner-office')
      .reply(({ request }) => {
        // Get the id and partnerOffice
        const id = request.body.id;
        const partnerOffice = cloneDeep(request.body.partnerOffice);

        // Prepare the updated partnerOffice
        let updatedPartnerOffice = null;

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

            // Store the updated partnerOffice
            updatedPartnerOffice = partnerOffices[index];
          }
        });

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerOffice - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/member/partner-office/partner-office')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

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

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