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

@Injectable({
  providedIn: 'root',
})
export class ReportUserSessionMockApi {
  private _userSessions: any[] = userSessionsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ UserSessions - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/report/user-session/user-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 userSessions
        let userSessions: any[] | null = cloneDeep(this._userSessions);

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

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

        // Paginate - Start
        const userSessionsLength = userSessions.length;

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

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

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

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

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

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

        // Clone the userSessions
        const userSessions = cloneDeep(this._userSessions);

        // Find the userSession
        const userSession = userSessions.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ UserSession - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/report/user-session/user-session')
      .reply(() => {
        // Generate a new userSession
        const newUserSession = {
          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 userSession
        this._userSessions.unshift(newUserSession);

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

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

        // Prepare the updated userSession
        let updatedUserSession = null;

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

            // Store the updated userSession
            updatedUserSession = userSessions[index];
          }
        });

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

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

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

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