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

@Injectable({
  providedIn: 'root',
})
export class MemberUnconnectedMockApi {
  private _unconnecteds: any[] = unconnectedsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Unconnecteds - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/member/unconnected/unconnecteds', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'signinId';
        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 unconnecteds
        let unconnecteds: any[] | null = cloneDeep(this._unconnecteds);

        // Sort the unconnecteds
        if (
          sort === 'id' ||
          sort === 'signinId' ||
          sort === 'nickname' ||
          sort === 'state'
        ) {
          unconnecteds.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 {
          unconnecteds.sort((a, b) =>
            order === 'asc' ? a[sort] - b[sort] : b[sort] - a[sort]
          );
        }

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

        // Paginate - Start
        const unconnectedsLength = unconnecteds.length;

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

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

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

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

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

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

        // Clone the unconnecteds
        const unconnecteds = cloneDeep(this._unconnecteds);

        // Find the unconnected
        const unconnected = unconnecteds.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Unconnected - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/unconnected/unconnected')
      .reply(() => {
        // Generate a new unconnected
        const newUnconnected = {
          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 unconnected
        this._unconnecteds.unshift(newUnconnected);

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

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

        // Prepare the updated unconnected
        let updatedUnconnected = null;

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

            // Store the updated unconnected
            updatedUnconnected = unconnecteds[index];
          }
        });

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

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

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

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