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

@Injectable({
  providedIn: 'root',
})
export class BoardNoticeMockApi {
  private _notices: any[] = noticesData;

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

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

  /**
   * Register Mock API handlers
   */
  registerHandlers(): void {
    // -----------------------------------------------------------------------------------------------------
    // @ Notices - GET
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onGet('api/apps/board/notice/notices', 300)
      .reply(({ request }) => {
        // Get available queries
        const search = request.params.get('search');

        const page = parseInt(request.params.get('page') ?? '1', 10);
        const size = parseInt(request.params.get('size') ?? '10', 10);

        // Clone the notices
        let notices: any[] | null = cloneDeep(this._notices);

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

        // Paginate - Start
        const noticesLength = notices.length;

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

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

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

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

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

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

        // Clone the notices
        const notices = cloneDeep(this._notices);

        // Find the notice
        const notice = notices.find((item: any) => item.id === id);

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

    // -----------------------------------------------------------------------------------------------------
    // @ Notice - POST
    // -----------------------------------------------------------------------------------------------------
    this._fuseMockApiService
      .onPost('api/apps/board/notice/notice')
      .reply(() => {
        // Generate a new notice
        const newNotice = {
          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 notice
        this._notices.unshift(newNotice);

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

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

        // Prepare the updated notice
        let updatedNotice = null;

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

            // Store the updated Notice
            updatedNotice = notices[index];
          }
        });

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

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

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

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