import EventBus from '../../Events/EventBus.js';
import Events from '../../Events/Events.js';
import MobileFiltersUI from './MobileFiltersUI.js';
import Utils from '../../Utils/Utils.js';
import FilterManager from '../FilterManager.js';

class HandleMobileFiltersBtns {

    _efxTimeout = null;

    constructor() {
        this._eventBus = EventBus.getInstance();
        this._init();
    }

    _init() {
        this._handleEvents();
    }

    _handleEvents() {
        const _this = this;
        jQuery('.fuse-open-mobile-filters').on('click', function(event) {
            event.preventDefault();
            MobileFiltersUI.getInstance().show();
        });

        jQuery('.close-filters-popup-btn').on('click', function(event) {
            event.preventDefault();
            MobileFiltersUI.getInstance().hide();
        })

        jQuery('.fusecommerce-filters-background-black').on('click', function(event) {
            event.preventDefault();
            MobileFiltersUI.getInstance().hide();
            event.stopPropagation();
        })

        jQuery('.fuse-apply-filters-popup-btn').on('click', function(event) {
            event.preventDefault();
            MobileFiltersUI.getInstance().hide();
            FilterManager.getInstance().triggerApplyFilters();
        })

        EventBus.getInstance().registerDynamicEvent({
            key: Events.SHOWING_PRODUCTS_COUNT,
            callback: (payload) => this._handleShowingProductsCount(payload)
        });
    }

    _handleShowingProductsCount(payload) {
        const { count } = payload;
        
        if (this._efxTimeout) {
            clearTimeout(this._efxTimeout);
        }

        jQuery('.fuse-apply-filters-popup-btn .fuse-loader-ui').removeClass('hidden');
        jQuery('.fuse-apply-filters-popup-btn .fuse-info').css('opacity', .5);
        this._efxTimeout = setTimeout(() => {
            jQuery('.fuse-apply-filters-popup-btn .fuse-loader-ui').addClass('hidden');
            jQuery('.fuse-apply-filters-popup-btn .fuse-info').css('opacity', 1);
            if (Utils.isValidNumber(count)) {
                jQuery('.fuse-apply-filters-popup-btn .fuse-show-products-count').html(count);
            } else {
                jQuery('.fuse-apply-filters-popup-btn .fuse-show-products-count').html('');
            }
        }, 1000);
    }
}
export default HandleMobileFiltersBtns;