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

@Injectable({
  providedIn: 'root',
})
export class GamePowerballMockApi {
  private _powerballs: any[] = powerballsData;

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

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

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

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

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

        // Paginate - Start
        const powerballsLength = powerballs.length;

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

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

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

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

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

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

        // Clone the powerballs
        const powerballs = cloneDeep(this._powerballs);

        // Find the powerball
        const powerball = powerballs.find((item: any) => item.id === id);

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

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

        // Unshift the new powerball
        this._powerballs.unshift(newPowerball);

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

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

        // Prepare the updated powerball
        let updatedPowerball = null;

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

            // Store the updated powerball
            updatedPowerball = powerballs[index];
          }
        });

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

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

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

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