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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerRecommendationMockApi {
  private _partnerRecommendations: any[] = partnerRecommendationsData;

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

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

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

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

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

        // Paginate - Start
        const partnerRecommendationsLength = partnerRecommendations.length;

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

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

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

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

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

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

        // Clone the partnerRecommendations
        const partnerRecommendations = cloneDeep(this._partnerRecommendations);

        // Find the partnerRecommendation
        const partnerRecommendation = partnerRecommendations.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerRecommendation - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner-recommendation/partner-recommendation')
      .reply(() => {
        // Generate a new partnerRecommendation
        const newPartnerRecommendation = {
          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 partnerRecommendation
        this._partnerRecommendations.unshift(newPartnerRecommendation);

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

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

        // Prepare the updated partnerRecommendation
        let updatedPartnerRecommendation = null;

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

              // Store the updated partnerRecommendation
              updatedPartnerRecommendation = partnerRecommendations[index];
            }
          }
        );

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

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

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

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