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

@Injectable({
  providedIn: 'root',
})
export class MemberCouponMoneyLogMockApi {
  private _couponMoneyLogs: any[] = couponMoneyLogsData;

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

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

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

        // Sort the couponMoneyLogs
        if (
          sort === 'issuedCouponId' ||
          sort === 'useCouponId' ||
          sort === 'retrieveCouponId'
        ) {
          couponMoneyLogs.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 {
          couponMoneyLogs.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const couponMoneyLogsLength = couponMoneyLogs.length;

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

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

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

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

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

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

        // Clone the couponMoneyLogs
        const couponMoneyLogs = cloneDeep(this._couponMoneyLogs);

        // Find the couponMoneyLog
        const couponMoneyLog = couponMoneyLogs.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ CouponMoneyLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/coupon-money-log/coupon-money-log')
      .reply(() => {
        // Generate a new couponMoneyLog
        const newCouponMoneyLog = {
          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 couponMoneyLog
        this._couponMoneyLogs.unshift(newCouponMoneyLog);

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

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

        // Prepare the updated couponMoneyLog
        let updatedCouponMoneyLog = null;

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

            // Store the updated couponMoneyLog
            updatedCouponMoneyLog = couponMoneyLogs[index];
          }
        });

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

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

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

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