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

@Injectable({
  providedIn: 'root',
})
export class GameEvolutionMockApi {
  private _evolutions: any[] = evolutionsData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Evolutions - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/game/evolution/evolutions', 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 evolutions
        let evolutions: any[] | null = cloneDeep(this._evolutions);

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

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

        // Paginate - Start
        const evolutionsLength = evolutions.length;

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

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

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

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

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

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

        // Clone the evolutions
        const evolutions = cloneDeep(this._evolutions);

        // Find the evolution
        const evolution = evolutions.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Evolution - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/gmae/evolution/evolution')
      .reply(() => {
        // Generate a new evolution
        const newEvolution = {
          id: FuseMockApiUtils.guid(),
          startDate: '',
          finishDate: '',
          totalBetting: '',
          winningMoney: '',
          proceedingMoney: '',
          calculate: '',
          index: '',
          division: '',
          rank: '',
          nickname: '',
          bettingProgress: '',
          odds: '',
          bettingMoney: '',
          hitMoney: '',
          bettingTime: '',
          result: '',
          delete: '',
        };

        // Unshift the new evolution
        this._evolutions.unshift(newEvolution);

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

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

        // Prepare the updated evolution
        let updatedEvolution = null;

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

            // Store the updated evolution
            updatedEvolution = evolutions[index];
          }
        });

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

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

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

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