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

@Injectable({
  providedIn: 'root',
})
export class MemberCouponLogMockApi {
  private _couponLogs: any[] = couponLogsData;

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

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

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

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

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

        // Paginate - Start
        const couponLogsLength = couponLogs.length;

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

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

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

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

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

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

        // Clone the couponLogs
        const couponLogs = cloneDeep(this._couponLogs);

        // Find the couponLog
        const couponLog = couponLogs.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ CouponLog - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/coupon-log/coupon-log')
      .reply(() => {
        // Generate a new couponLog
        const newCouponLog = {
          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 couponLog
        this._couponLogs.unshift(newCouponLog);

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

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

        // Prepare the updated couponLog
        let updatedCouponLog = null;

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

            // Store the updated couponLog
            updatedCouponLog = couponLogs[index];
          }
        });

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

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

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

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