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

@Injectable({
  providedIn: 'root',
})
export class ReportAdminSessionMockApi {
  private _adminSessions: any[] = adminSessionsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ AdminSessions - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/admin-session/admin-sessions', 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 adminSessions
        let adminSessions: any[] | null = cloneDeep(this._adminSessions);

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

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

        // Paginate - Start
        const adminSessionsLength = adminSessions.length;

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

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

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

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

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

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

        // Clone the adminSessions
        const adminSessions = cloneDeep(this._adminSessions);

        // Find the adminSession
        const adminSession = adminSessions.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ AdminSession - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/admin-session/admin-session')
      .reply(() => {
        // Generate a new adminSession
        const newAdminSession = {
          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 adminSession
        this._adminSessions.unshift(newAdminSession);

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

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

        // Prepare the updated adminSession
        let updatedAdminSession = null;

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

            // Store the updated adminSession
            updatedAdminSession = adminSessions[index];
          }
        });

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

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

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

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