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

@Injectable({
  providedIn: 'root',
})
export class BoardCustomerMockApi {
  private _customers: any[] = customersData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Customers - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/board/customer/customers', 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 customers
        let customers: any[] | null = cloneDeep(this._customers);

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

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

        // Paginate - Start
        const customersLength = customers.length;

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

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

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

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

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

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

        // Clone the customers
        const customers = cloneDeep(this._customers);

        // Find the customer
        const customer = customers.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Customer - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/board/customer/customer')
      .reply(() => {
        // Generate a new customer
        const newCustomer = {
          id: FuseMockApiUtils.guid(),
          signinId: '',
          nickname: '',
          idx: 0,
          title: '',
          level: '',
          memo: '',
          finalOwnCharge: 0,
          finalSigninDate: '2022-06-21T17:16',
          highRank: '',
          site: '',
          views: 0,
          writeDate: '2022-06-21T13:34',
          answer: '미해결',
          state: '노출',
        };

        // Unshift the new customer
        this._customers.unshift(newCustomer);

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

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

        // Prepare the updated customer
        let updatedCustomer = null;

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

            // Store the updated customer
            updatedCustomer = customers[index];
          }
        });

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

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

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

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