/**
 * For the full copyright and license information, please view the
 * docs/licenses/LICENSE.txt file that was distributed with this source code.
 */

import createOrderMap from '@pages/order/create/create-order-map';
import CustomerRenderer from '@pages/order/create/customer-renderer';
import {EventEmitter} from '@components/event-emitter';
import eventMap from '@pages/order/create/event-map';
import Router from '@components/router';

const {$} = window;

/**
 * Responsible for customers managing. (search, select, get customer info etc.)
 */
export default class CustomerManager {
  customerId: null | number;

  activeSearchRequest: null | JQuery.jqXHR;

  router: Router;

  $container: JQuery;

  $searchInput: JQuery;

  $customerSearchResultBlock: JQuery;

  customerRenderer: CustomerRenderer;

  constructor() {
    this.customerId = null;
    this.activeSearchRequest = null;

    this.router = new Router();
    this.$container = $(createOrderMap.customerSearchBlock);
    this.$searchInput = $(createOrderMap.customerSearchInput);
    this.$customerSearchResultBlock = $(
      createOrderMap.customerSearchResultsBlock,
    );
    this.customerRenderer = new CustomerRenderer();

    this.initListeners();
    this.initAddCustomerIframe();
  }

  /**
   * Initializes event listeners
   *
   * @private
   */
  private initListeners(): void {
    this.$container.on('click', createOrderMap.changeCustomerBtn, () => this.changeCustomer(),
    );
    this.onCustomerSearch();
    this.onCustomerSelect();
    this.onCustomersNotFound();
  }

  /**
   * @private
   */
  private initAddCustomerIframe(): void {
    $(createOrderMap.customerAddBtn).fancybox({
      type: 'iframe',
      width: '90%',
      height: '90%',
    });
  }

  /**
   * Listens for customer search event
   *
   * @private
   */
  private onCustomerSearch(): void {
    EventEmitter.on(eventMap.customerSearched, (response) => {
      this.activeSearchRequest = null;
      this.customerRenderer.hideSearchingCustomers();

      if (response.customers.length === 0) {
        EventEmitter.emit(eventMap.customersNotFound);

        return;
      }

      this.customerRenderer.renderSearchResults(response.customers);
    });
  }

  /**
   * Listens for event of when no customers were found by search
   *
   * @private
   */
  private onCustomersNotFound(): void {
    EventEmitter.on(eventMap.customersNotFound, () => {
      this.customerRenderer.showNotFoundCustomers();
      this.customerRenderer.hideCheckoutHistoryBlock();
    });
  }

  /**
   * Listens for customer select event
   *
   * @private
   */
  private onCustomerSelect(): void {
    EventEmitter.on(eventMap.customerSelected, (event) => {
      const $chooseBtn = $(event.currentTarget);
      this.customerId = $chooseBtn.data('customer-id');

      const createAddressUrl = this.router.generate('admin_addresses_create', {
        liteDisplaying: 1,
        submitFormAjax: 1,
        id_customer: this.customerId,
      });
      $(createOrderMap.addressAddBtn).attr('href', createAddressUrl);

      this.customerRenderer.displaySelectedCustomerBlock($chooseBtn);
    });
  }

  /**
   * Handles use case when customer is changed
   *
   * @private
   */
  private changeCustomer(): void {
    this.customerRenderer.showCustomerSearch();
  }

  /**
   * Loads customer carts list
   *
   * @param currentCartId
   */
  loadCustomerCarts(currentCartId: string): void {
    const {customerId} = this;

    this.customerRenderer.showLoadingCarts();
    $.get(this.router.generate('admin_customers_carts', {customerId}))
      .then((response) => {
        this.customerRenderer.renderCarts(response.carts, currentCartId);
      })
      .catch((e: Record<string, any>) => {
        window.showErrorMessage(e.responseJSON.message);
      });
  }

  /**
   * Loads customer orders list
   */
  loadCustomerOrders(): void {
    const {customerId} = this;

    this.customerRenderer.showLoadingOrders();
    $.get(this.router.generate('admin_customers_orders', {customerId}))
      .then((response) => {
        this.customerRenderer.renderOrders(response.orders);
      })
      .catch((e: Record<string, any>) => {
        window.showErrorMessage(e.responseJSON.message);
      });
  }

  /**
   * @param {Event} chooseCustomerEvent
   *
   * @return {Number}
   */
  selectCustomer(chooseCustomerEvent: JQueryEventObject): number {
    EventEmitter.emit(eventMap.customerSelected, chooseCustomerEvent);

    return <number> this.customerId;
  }

  /**
   * Searches for customers
   *
   */
  search(searchPhrase: string): void {
    if (searchPhrase.length === 0) {
      return;
    }

    if (this.activeSearchRequest !== null) {
      this.activeSearchRequest.abort();
    }

    this.customerRenderer.clearShownCustomers();
    this.customerRenderer.hideNotFoundCustomers();
    this.customerRenderer.showSearchingCustomers();
    const $searchRequest = $.get(
      this.router.generate('admin_customers_search'),
      {
        customer_search: searchPhrase,
      },
    );
    this.activeSearchRequest = $searchRequest;

    $searchRequest
      .then((response) => {
        EventEmitter.emit(eventMap.customerSearched, response);
      })
      .catch((response: JQuery.jqXHR) => {
        if (response.statusText === 'abort') {
          return;
        }

        window.showErrorMessage(response.responseJSON.message);
      });
  }
}
