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

@Injectable({
  providedIn: 'root',
})
export class MemberPartnerBranchMockApi {
  private _partnerBranchs: any[] = partnerBranchsData;

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

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

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

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

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

        // Paginate - Start
        const partnerBranchsLength = partnerBranchs.length;

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

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

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

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

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

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

        // Clone the partnerBranchs
        const partnerBranchs = cloneDeep(this._partnerBranchs);

        // Find the partnerBranch
        const partnerBranch = partnerBranchs.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ PartnerBranch - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/partner-branch/partner-branch')
      .reply(() => {
        // Generate a new partnerBranch
        const newPartnerBranch = {
          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 partnerBranch
        this._partnerBranchs.unshift(newPartnerBranch);

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

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

        // Prepare the updated partnerBranch
        let updatedPartnerBranch = null;

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

            // Store the updated partnerBranch
            updatedPartnerBranch = partnerBranchs[index];
          }
        });

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

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

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

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