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

@Injectable({
  providedIn: 'root',
})
export class MemberCurrentUserMockApi {
  private _currentUsers: any[] = currentUsersData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ CurrentUsers - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/member/current-user/current-users', 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 currentUsers
        let currentUsers: any[] | null = cloneDeep(this._currentUsers);

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

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

        // Paginate - Start
        const currentUsersLength = currentUsers.length;

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

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

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

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

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

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

        // Clone the currentUsers
        const currentUsers = cloneDeep(this._currentUsers);

        // Find the currentUser
        const currentUser = currentUsers.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ CurrentUser - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/member/current-user/current-user')
      .reply(() => {
        // Generate a new currentUser
        const newCurrentUser = {
          id: FuseMockApiUtils.guid(),
          signinId: '',
          nickname: '',
          currentLocation: '',
          gameMoney: 0,
          highRank: '',
          index: 0,
          level: '',
          ownCash: 0,
          ownComp: 0,
          rank: '',
          siteAddress: '',
        };

        // Unshift the new currentUser
        this._currentUsers.unshift(newCurrentUser);

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

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

        // Prepare the updated currentUser
        let updatedCurrentUser = null;

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

            // Store the updated currentUser
            updatedCurrentUser = currentUsers[index];
          }
        });

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

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

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

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