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

@Injectable({
  providedIn: 'root',
})
export class MemberUserMockApi {
  private _users: any[] = usersData;

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

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

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

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

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

        // Paginate - Start
        const usersLength = users.length;

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

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

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

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

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

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

        // Clone the users
        const users = cloneDeep(this._users);

        // Find the user
        const user = users.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ User - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService.onPost('api/apps/member/user/user').reply(() => {
      // Generate a new user
      const newUser = {
        id: FuseMockApiUtils.guid(),
        signinId: '',
        signinPw: '',
        exchangePw: '',
        nickname: '',
        highRank: '',
        rank: '',
        level: '',
        accountHolder: '',
        phoneNumber: '',
        ownCash: 0,
        ownComp: 0,
        ownCoupon: 0,
        gameMoney: 0,
        todayComp: 0,
        totalDeposit: 0,
        totalWithdraw: 0,
        balance: 0,
        registrationDate: '2022-01-01T16:00',
        finalSigninDate: '2022-01-01T16:00',
        ip: '192.168.1.9',
        state: '정상',
      };

      // Unshift the new user
      this._users.unshift(newUser);

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

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

        // Prepare the updated user
        let updatedUser = null;

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

            // Store the updated user
            updatedUser = users[index];
          }
        });

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

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

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

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