import {hideLoader, showLoader} from "./utils/loader";
import {createEvent} from "./utils/create-event";

const Handlebars = require("hbsfy/runtime");
import accountHubCard from '../../components/account-families/account-hub-card.hbs'

Handlebars.registerPartial('checkbox', require("../../elements/checkbox.hbs"));
Handlebars.registerHelper('unlessCond', function (v1, operator, v2, options) {
  if (operator === '&&') {
    return (v1 && v2) ?  options.inverse(this) : options.fn(this);
  }
});
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
  if (operator === '||') {
    return (v1 || v2) ? options.fn(this) : options.inverse(this);
  }
});

var Wick = window.Wick || {};
Wick.AccountHub = {
  ERROR_MESSAGE: 'Please select a member(s)',
  LOAD_MORE_EVENT: 'loadMore',
  HIDDEN_CLASS_NAME: 'd-none',
  initialPageNumber: 0,
  el: {
    $accountHubRemove: $('.account-hub-remove'),
    accountHubRemoveClass: 'account-hub-remove',
    $accountHub: $('.account-hub'),
    loader: '.account-hub .content .loader-wrapper',
    cancelBtnClass: '.btn-cancel-remove',
    $btnRemove: $('.btn-remove'),
    $accountHubMembers: $('.account-hub__members'),
    $loadMoreBtn: $('.btn-load-more'),
    $loadMoreBlock: $('.account-hub__load'),
    $accountHubList: $('.account-hub__list'),
    $globalMessages: $('.globalMessages'),
    $sortOptions: $('#sortOptions'),
    accountHubListInput: $('.account-hub__list input[type="checkbox"]'),
  },
  checkIsNoOneMemberSelected() {
    let isNoOneChecked = true;
    Wick.AccountHub.el.$accountHubMembers.find('input').each((_, el) => {
      if ($(el).prop('checked') === true) {
        isNoOneChecked = false;
      }
    })
    return isNoOneChecked;
  },
  isNotificationContainerExist() {
    return !!Wick.AccountHub.el.$globalMessages.find('.container').length;
  },
  addNotificationContainer() {
    const isContainerExist = Wick.AccountHub.isNotificationContainerExist();
    isContainerExist || Wick.AccountHub.el.$globalMessages.append('<div class="container"></div>')
  },
  removeMembers(e) {
    if (Wick.AccountHub.checkIsNoOneMemberSelected()) {
      e.stopPropagation();

      Wick.AccountHub.addNotificationContainer();
      Wick.Notification.show({
        text: Wick.AccountHub.ERROR_MESSAGE,
        container: '.globalMessages .container',
        type: 'error',
      });
    }
  },
  unselectAllCheckboxesOnPageLeave() {
    $(window).on('beforeunload', function(){
      $(Wick.AccountHub.el.accountHubListInput).filter(':checked').prop('checked', false).addClass('fake-checked');
    });
  },
  loadMore() {
    showLoader(Wick.AccountHub.el.loader);

    return new Promise((resolve, reject) => {
      const eventDetail = {resolve, reject};
      const payload = {
        page: ++Wick.AccountHub.initialPageNumber,
        sort: Wick.AccountHub.el.$sortOptions.val() || '',
      };
      const event = createEvent(Wick.AccountHub.LOAD_MORE_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then((membersData) => {
        Wick.AccountHub.showNewMembers(membersData);
        Wick.AccountHub.toggleLoadMoreBtn(membersData);
      })
      .finally(() => {
        hideLoader(Wick.AccountHub.el.loader);
      })
  },
  toggleLoadMoreBtn(membersData) {
    if (membersData.canLoadMore) {
      Wick.AccountHub.el.$loadMoreBlock.removeClass(Wick.AccountHub.HIDDEN_CLASS_NAME);
    } else {
      Wick.AccountHub.el.$loadMoreBlock.addClass(Wick.AccountHub.HIDDEN_CLASS_NAME);
    }
  },
  showNewMembers(membersData) {
    const isRemovePage = Wick.AccountHub.el.$accountHub.hasClass(Wick.AccountHub.el.accountHubRemoveClass);
    membersData.members.forEach((el) => {
      $(Wick.AccountHub.el.$accountHubList).append(
        accountHubCard({...el, remove: isRemovePage})
      );
    });
  },
  initAccountHubRemove() {
    if (!Wick.AccountHub.el.$accountHubRemove.length) {
      return;
    }

    Wick.LeaveEvent.bindEvent(Wick.AccountHub.el.$accountHubList, Wick.AccountHub.el.cancelBtnClass);
    Wick.AccountHub.el.$btnRemove.click((e) => {
      Wick.LeaveEvent.proceedBrowserLeave = false;
      Wick.AccountHub.removeMembers(e);
    });

    Wick.AccountHub.unselectAllCheckboxesOnPageLeave();
  },
  initAccountHub() {
    if (!Wick.AccountHub.el.$accountHub.length) {
      return;
    }
    Wick.AccountHub.el.$loadMoreBtn.on('click', Wick.AccountHub.loadMore);
  }
}
