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

@Injectable({
  providedIn: 'root',
})
export class BoardMessageMockApi {
  private _messages: any[] = messagesData;

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

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

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

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

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

        // Paginate - Start
        const messagesLength = messages.length;

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

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

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

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

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

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

        // Clone the messages
        const messages = cloneDeep(this._messages);

        // Find the message
        const message = messages.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Message - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/board/message/message')
      .reply(() => {
        // Generate a new message
        const newMessage = {
          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 message
        this._messages.unshift(newMessage);

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

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

        // Prepare the updated message
        let updatedMessage = null;

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

            // Store the updated Message
            updatedMessage = messages[index];
          }
        });

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

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

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

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