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

@Injectable({
  providedIn: 'root',
})
export class MemberCasinomoneyMockApi {
  private _casinomoneys: any[] = casinomoneysData;

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

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

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

        // Sort the casinomoneys
        if (sort === 'sku' || sort === 'name' || sort === 'active') {
          casinomoneys.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 {
          casinomoneys.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const casinomoneysLength = casinomoneys.length;

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

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

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

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

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

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

        // Clone the casinomoneys
        const casinomoneys = cloneDeep(this._casinomoneys);

        // Find the casinomoney
        const casinomoney = casinomoneys.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Casinomoney - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/casinomoney/casinomoney')
      .reply(() => {
        // Generate a new casinomoney
        const newCasinomoney = {
          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 casinomoney
        this._casinomoneys.unshift(newCasinomoney);

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

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

        // Prepare the updated casinomoney
        let updatedCasinomoney = null;

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

            // Store the updated casinomoney
            updatedCasinomoney = casinomoneys[index];
          }
        });

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

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

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

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