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

@Injectable({
  providedIn: 'root',
})
export class ReportPaymentLogMockApi {
  private _paymentLogs: any[] = paymentLogsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ PaymentLogs - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/payment-log/payment-logs', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'giveId';
        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 paymentLogs
        let paymentLogs: any[] | null = cloneDeep(this._paymentLogs);

        // Sort the paymentLogs
        if (sort === 'giveId' || sort === 'takeId' || sort === 'idx') {
          paymentLogs.sort((a, b) => {
            const fieldA = a[sort].toString().toUpperCase();
            const fieldB = b[sort].toString().toUpperCase();
            return order === 'asc'
              ? fieldA.localePaymentare(fieldB)
              : fieldB.localePaymentare(fieldA);
          });
        } else {
          paymentLogs.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const paymentLogsLength = paymentLogs.length;

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

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

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

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

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

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

        // Clone the paymentLogs
        const paymentLogs = cloneDeep(this._paymentLogs);

        // Find the paymentLog
        const paymentLog = paymentLogs.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ PaymentLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/payment-log/payment-log')
      .reply(() => {
        // Generate a new paymentLog
        const newPaymentLog = {
          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 paymentLog
        this._paymentLogs.unshift(newPaymentLog);

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

    // -----------------------------------------------------------------------------------------------------
    // @ PaymentLog - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/report/payment-log/payment-log')
      .reply(({ request }) => {
        // Get the id and paymentLog
        const id = request.body.id;
        const paymentLog = cloneDeep(request.body.paymentLog);

        // Prepare the updated paymentLog
        let updatedPaymentLog = null;

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

            // Store the updated paymentLog
            updatedPaymentLog = paymentLogs[index];
          }
        });

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

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

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

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