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

@Injectable({
  providedIn: 'root',
})
export class ReportDailyPartnerMockApi {
  private _dailyPartners: any[] = dailyPartnersData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ DailyPartners - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/daily-partners', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'lastDayHoldingMoney';
        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 dailyPartners
        let dailyPartners: any[] | null = cloneDeep(this._dailyPartners);

        // Sort the dailys
        if (
          sort === 'lastDayHoldingMoney' ||
          sort === 'memberCharge' ||
          sort === 'memberExchange'
        ) {
          dailyPartners.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 {
          dailyPartners.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }
        // If search exists...
        if (search) {
          // Filter the dailyPartners
          dailyPartners = dailyPartners.filter(
            (contact: any) =>
              contact.name &&
              contact.name.toLowerCase().includes(search.toLowerCase())
          );
        }

        // Paginate - Start
        const dailysLength = dailyPartners.length;

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

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

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

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

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

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

        // Clone the dailyPartners
        const dailyPartners = cloneDeep(this._dailyPartners);

        // Find the dailyPartner
        const dailyPartner = dailyPartners.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ DailyPartner - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/daily-partner')
      .reply(() => {
        // Generate a new dailyPartner
        const newDailyPartner = {
          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 dailyPartner
        this._dailyPartners.unshift(newDailyPartner);

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

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

        // Prepare the updated dailyPartner
        let updatedDailyPartner = null;

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

            // Store the updated dailyPartner
            updatedDailyPartner = dailyPartners[index];
          }
        });

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

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

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

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