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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerDivisionMockApi {
  private _partnerDivisions: any[] = partnerDivisionsData;

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

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

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

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

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

        // Paginate - Start
        const partnerDivisionsLength = partnerDivisions.length;

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

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

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

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

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

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

        // Clone the partnerDivisions
        const partnerDivisions = cloneDeep(this._partnerDivisions);

        // Find the partnerDivision
        const partnerDivision = partnerDivisions.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerDivision - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner-division/partner-division')
      .reply(() => {
        // Generate a new partnerDivision
        const newPartnerDivision = {
          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 partnerDivision
        this._partnerDivisions.unshift(newPartnerDivision);

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

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

        // Prepare the updated partnerDivision
        let updatedPartnerDivision = null;

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

            // Store the updated partnerDivision
            updatedPartnerDivision = partnerDivisions[index];
          }
        });

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

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

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

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