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

@Injectable({
  providedIn: 'root',
})
export class MemberCouponMockApi {
  private _coupons: any[] = couponsData;

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

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

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

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

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

        // Paginate - Start
        const couponsLength = coupons.length;

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

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

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

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

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

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

        // Clone the coupons
        const coupons = cloneDeep(this._coupons);

        // Find the coupon
        const coupon = coupons.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Coupon - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/coupon/coupon')
      .reply(() => {
        // Generate a new coupon
        const newCoupon = {
          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 coupon
        this._coupons.unshift(newCoupon);

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

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

        // Prepare the updated coupon
        let updatedCoupon = null;

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

            // Store the updated coupon
            updatedCoupon = coupons[index];
          }
        });

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

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

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

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