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

@Injectable({
  providedIn: 'root',
})
export class BoardPopupMockApi {
  private _popups: any[] = popupsData;

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

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

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

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

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

        // Paginate - Start
        const popupsLength = popups.length;

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

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

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

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

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

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

        // Clone the popups
        const popups = cloneDeep(this._popups);

        // Find the popup
        const popup = popups.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Popup - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService.onPost('api/apps/board/popup/popup').reply(() => {
      // Generate a new popup
      const newPopup = {
        id: FuseMockApiUtils.guid(),
        category: '',
        name: 'A New User',
        description: '',
        tags: [],
        sku: '',
        barcode: '',
        brand: '',
        vendor: '',
        stock: '',
        reserved: '',
        cost: '',
        basePrice: '',
        taxPercent: '',
        price: '',
        weight: '',
        thumbnail: '',
        images: [],
        active: false,
      };

      // Unshift the new popup
      this._popups.unshift(newPopup);

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

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

        // Prepare the updated popup
        let updatedPopup = null;

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

            // Store the updated popup
            updatedPopup = popups[index];
          }
        });

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

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

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

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