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-moneylog/coupon-moneylogs', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'name';
        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 === 'sku' || sort === 'name' || sort === 'active') {
          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-moneylog/coupon-moneylog')
      .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-moneylog/coupon-moneylog')
      .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-moneylog/coupon-moneylog')
      .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-moneylog/coupon-moneylog')
      .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];
      });
  }
}
