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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerStoreMockApi {
  private _partnerStores: any[] = partnerStoresData;

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

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

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

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

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

        // Paginate - Start
        const partnerStoresLength = partnerStores.length;

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

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

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

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

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

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

        // Clone the partnerStores
        const partnerStores = cloneDeep(this._partnerStores);

        // Find the partnerStore
        const partnerStore = partnerStores.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerStore - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner-store/partner-store')
      .reply(() => {
        // Generate a new partnerStore
        const newPartnerStore = {
          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 partnerStore
        this._partnerStores.unshift(newPartnerStore);

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

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

        // Prepare the updated partnerStore
        let updatedPartnerStore = null;

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

            // Store the updated partnerStore
            updatedPartnerStore = partnerStores[index];
          }
        });

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

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

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

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