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

@Injectable({
  providedIn: 'root',
})
export class ReportDuplicatedSessionMockApi {
  private _duplicatedSessions: any[] = duplicatedSessionsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ DuplicatedSessions - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/duplicated-session/duplicated-sessions', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');
        const sort = request.params.get('sort') || 'overlapCount';
        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 duplicatedSessions
        let duplicatedSessions: any[] | null = cloneDeep(
          this._duplicatedSessions
        );

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

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

        // Paginate - Start
        const duplicatedSessionsLength = duplicatedSessions.length;

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

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

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

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

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

    // -----------------------------------------------------------------------------------------------------
    // @ DuplicatedSession - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/duplicated-session/duplicated-session')
      .reply(({ request }) => {
        // Get the id from the params
        const id = request.params.get('id');

        // Clone the duplicatedSessions
        const duplicatedSessions = cloneDeep(this._duplicatedSessions);

        // Find the duplicatedSession
        const duplicatedSession = duplicatedSessions.find(
          (item: any) => item.id === id
        );

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

    // -----------------------------------------------------------------------------------------------------
    // @ DuplicatedSession - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/duplicated-session/duplicated-session')
      .reply(() => {
        // Generate a new duplicatedSession
        const newDuplicatedSession = {
          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 duplicatedSession
        this._duplicatedSessions.unshift(newDuplicatedSession);

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

    // -----------------------------------------------------------------------------------------------------
    // @ DuplicatedSession - PATCH
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPatch('api/apps/report/duplicated-session/duplicated-session')
      .reply(({ request }) => {
        // Get the id and duplicatedSession
        const id = request.body.id;
        const duplicatedSession = cloneDeep(request.body.duplicatedSession);

        // Prepare the updated duplicatedSession
        let updatedDuplicatedSession = null;

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

            // Store the updated duplicatedSession
            updatedDuplicatedSession = duplicatedSessions[index];
          }
        });

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

    // -----------------------------------------------------------------------------------------------------
    // @ DuplicatedSession - DELETE
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onDelete('api/apps/report/duplicated-session/duplicated-session')
      .reply(({ request }) => {
        // Get the id
        const id = request.params.get('id');

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

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