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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerMockApi {
  private _partners: any[] = partnersData;

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

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

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

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

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

        // Paginate - Start
        const partnersLength = partners.length;

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

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

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

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

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

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

        // Clone the partners
        const partners = cloneDeep(this._partners);

        // Find the partner
        const partner = partners.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Partner - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner/partner')
      .reply(() => {
        // Generate a new partner
        const newPartner = {
          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 partner
        this._partners.unshift(newPartner);

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

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

        // Prepare the updated partner
        let updatedPartner = null;

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

            // Store the updated partner
            updatedPartner = partners[index];
          }
        });

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

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

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

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