Source: components/filter/filter-tree/filter-style/filter-tree-style4.js

import jQ from 'jquery';

import FilterTree from "../filter-tree";
import Settings from "../../../../helpers/settings";
import FilterTreeEnum from "../../../../enum/filter-tree-enum";
import Utils from "../../../../helpers/utils";
import Class from "../../../../helpers/class";
import Labels from "../../../../helpers/labels";
import Globals from "../../../../helpers/globals";
import FilterOptionEnum from "../../../../enum/filter-option-enum";
import Filter from "../../filter";

/**
 * Filter tree style 4
 * Applies to veritcal, on mobile only
 * @extends FilterTree
 */
class FilterTreeStyle4 extends FilterTree {
  constructor(id, filterTreeType) {
    super(id, filterTreeType);
    this.style = 'style4';

    this.selector.clearAllButtonContainer = '.boost-pfs-filter-mobile-toolbar-right';
    this.selector.backButton = '.boost-pfs-filter-back-btn';
    this.selector.refineByOnTitle = '.boost-pfs-filter-selected-items-mobile';
    this.selector.headerTitle = '.bc-sf-filter-mobile-toolbar-header';
        this.selector.headerClose = '.boost-pfs-filter-close';

    this.style4ActiveFilterOption = null;
    Settings.activeFilterScrollbarMobile = false;
  }

  init() {
    super.init();
    if (jQ(this.idSelector).length > 0) {
      jQ(this.idSelector).addClass('boost-pfs-filter-tree-mobile-style4').addClass('boost-pfs-filter-tree-mobile-sticky');
      if(Settings.getSettingValue('general.filterTreeMobileStyleFullWidth')){
        jQ(this.idSelector).addClass('boost-pfs-filter-tree-mobile-full-width-style')
      }
    }
  }

  getHeaderTemplate() {
    return `
      <div class="boost-pfs-filter-mobile-toolbar">
                <div class="bc-sf-filter-mobile-toolbar-header">{{label.refineMobile}}</div>
        <div class="boost-pfs-filter-mobile-toolbar-items">
          <div class="boost-pfs-filter-mobile-toolbar-left">
            <a href="javascript:;" class="{{class.closeFilterButton}}"><span>{{label.close}}</span></a>
            <a href="javascript:;" class="boost-pfs-filter-back-btn">{{label.apply}}</a>
          </div>
          <div class="boost-pfs-filter-mobile-toolbar-right">
            {{clearButton}}
          </div>
        </div>
      </div>
    `;
  }

  render() {
    super.render();
    if (this.$element && Utils.isMobile()) {
      // Find the current active filter option (in case of switching collection/new filter tree)
      var activeFilterOption = null;
      this.filterOptions.forEach(filterOption => {
        if (this.style4ActiveFilterOption
          && this.style4ActiveFilterOption.filterOptionId == filterOption.filterOptionId) {
          activeFilterOption = filterOption;
        }
      })
      this.style4ActiveFilterOption = activeFilterOption;

      // Render filter tree header
      this.renderFilterTreeHeader();

      // Render filter tree footer
      this.renderFilterTreeFooter();

      // Render filter option collapse/not collapse
      this.renderFilterOptionCollapse();

      // Render filter option's clear button on header
      this.renderFilterOptionClear();

      // Render selected filter option on title
      this.renderRefineByOnTitle();
    }
  }

  bindEvents() {
    super.bindEvents();
    if (this.$element && Utils.isMobile()) {
      // Bind back button event
      this.$element.find(this.selector.backButton).on('click', this.closeFilterOption.bind(this));

      this.filterOptions.forEach(filterOption => {
        // Bind filter option title click event
        if (filterOption.$filterOptionTitleElement) {
          filterOption.$filterOptionTitleElement.off('click');
          filterOption.$filterOptionTitleElement.on('click', this.openFilterOption.bind(this, filterOption));
                    
        }
      })
            
            
            
            // Fix issue scroll on iphone
//            if (/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)) {
//                var temp_div = document.getElementById('temp_div');
//                if (temp_div == null) {
//                    temp_div = document.createElement('div');   
//                    temp_div.setAttribute('id', 'temp_div');
//                    temp_div.style.position = 'fixed';
//                    temp_div.style.height = '100vh';
//                    temp_div.style.width = 0;
//                    temp_div.style.top = 0;
//                    jQ('body').append(temp_div)
//                }                                
//                
//                if(temp_div.offsetHeight > window.innerHeight) {
//                    jQ('.boost-pfs-filter-options-wrapper').addClass('boost-pfs-fitler-height-mobile')
//                } else {
//                    jQ('.boost-pfs-filter-options-wrapper').removeClass('boost-pfs-fitler-height-mobile')
//                }
//                jQ(window).resize(function(){
//                    temp_div = document.getElementById('temp_div');
//
//                    if(temp_div.offsetHeight > window.innerHeight) {
//                        jQ('.boost-pfs-filter-options-wrapper').addClass('boost-pfs-fitler-height-mobile')
//                    } else {
//                        jQ('.boost-pfs-filter-options-wrapper').removeClass('boost-pfs-fitler-height-mobile')
//                    }
//                })
//            }
            
    }
  }

  renderFilterTreeHeader() {
    if (this.style4ActiveFilterOption) {
      // Change header title to filter option's title
      this.$element.find(this.selector.headerTitle).html(this.style4ActiveFilterOption.label);
      // Show back button
      this.$element.find(this.selector.backButton).show();
            // Hide Close button
            this.$element.find(this.selector.headerClose).hide();
    } else {
      // Change header title to 'Refine by'
      this.$element.find(this.selector.headerTitle).html(Labels.refineMobile);
      // Hide back button
      this.$element.find(this.selector.backButton).hide();
            // Show Close button
            this.$element.find(this.selector.headerClose).show();
    }
  }

  renderFilterTreeFooter() {
    var numberResult = this.parent && this.parent.data ? ' ('+ this.parent.data.total_product +')' : '';
    this.$element.find('.' + Class.showResultFilterButton).html(Labels.showResult + '<span class="boost-pfs-number-result">' + numberResult + '</span>');
  }

  renderFilterOptionCollapse() {
    // Set visible title and content
    this.filterOptions.forEach(filterOption => {
      if (filterOption.$filterOptionTitleElement && filterOption.$filterOptionContentElement && filterOption.collapse) {
        filterOption.$element.removeClass('boost-pfs-filter-option-collapsed');
        var $tiltle = filterOption.$element.find('.boost-pfs-filter-option-title');
        var $content = filterOption.$filterOptionContentElement;

        if (this.style4ActiveFilterOption) {
          if (filterOption == this.style4ActiveFilterOption) {
            $tiltle.hide();
            $content.show();
          } else {
            $tiltle.hide();
            $content.hide();
          }
        } else {
          $tiltle.show();
          $content.hide();
        }
      }
    })
  }

  renderFilterOptionClear() {
    var $clearAllButton = this.clearAllButton.$element;
    var $clearContainer = this.$element.find(this.selector.clearAllButtonContainer);
    if (!$clearContainer) return;

    if ($clearAllButton) {
      // Check if have active filter option
      if (this.style4ActiveFilterOption != null || !Globals.hasFilterOptionParam) {
        // Remove clear all button
        $clearAllButton.detach();
      } else {
        // Append clear all button
        $clearContainer.append($clearAllButton);
      }
    }

    // Remove all filter option clear button
    this.filterOptions.forEach(filterOption => {
      if (filterOption.clearButton && filterOption.clearButton.$element) {
        filterOption.clearButton.$element.detach();
      }
    })

    // Append active filter option clear button
    if (this.style4ActiveFilterOption && this.style4ActiveFilterOption.clearButton && this.style4ActiveFilterOption.clearButton.$element) {
      $clearContainer.append(this.style4ActiveFilterOption.clearButton.$element);
    }
  }

  renderRefineByOnTitle() {
    // Render refine by label on each filter option
    this.filterOptions.forEach(filterOption => {

      if (filterOption.$element) {
        var labelText = '';
        // Multi level collection label
        if (filterOption.filterOptionId.startsWith(Globals.prefix + '_c_')) {
          var filterItems = filterOption.displayType == FilterOptionEnum.DisplayType.MULTI_LEVEL_COLLECTIONS ? filterOption.allNestedFilterItems : filterOption.filterItems;
          if (filterItems && filterItems.size > 0) {
            var collectionLabel = '';
            var tagLabels = [];
            filterItems.forEach((filterItem) => {
              if (filterItem.isSelected) {
                if (filterItem.level == 2 || filterItem.level == 3) {
                  tagLabels.push(filterItem.label);
                } else {
                  collectionLabel = filterItem.label;
                }
              }
            })
            if (collectionLabel && tagLabels.length > 0) {
              labelText = collectionLabel + ': ' + tagLabels.join(', ');
            } else {
              labelText = collectionLabel;
            }
          }

        // Other filter option label
        } else if (this.refineBy && this.refineBy.refineByItems) {
          var refineByLabels = [];
          this.refineBy.refineByItems.forEach(refineByItem => {
            if (refineByItem.filterOptionId == filterOption.filterOptionId) {
              var label = refineByItem.label;
              if (label) {
                refineByLabels.push(label);
              }
            }
          })
          labelText = refineByLabels.join(', ');
        }

        var labelHtml = labelText ? '<span>' + labelText + '</span>' : '';
        filterOption.$element.find(this.selector.refineByOnTitle).html(labelHtml);
      }
    })
  }

  /**
   * On clicking on one filter option, shows a new screen with the values
   * @param {FilterOption} activeFilterOption - The clicked filter option component
   */
  openFilterOption(activeFilterOption) {
    // Render collapse state of all filter options
    this.style4ActiveFilterOption = activeFilterOption;
    this.renderFilterTreeHeader();
    this.renderFilterOptionCollapse();
    this.renderFilterOptionClear();
        
        // Math height for mobile toolbar
        var heightToolbarMobile = jQ('.boost-pfs-filter-mobile-toolbar').height();
        jQ('.boost-pfs-filter-options-wrapper').css('top', heightToolbarMobile + 'px');
  }

  closeFilterOption() {
    // Render collapse state of all filter options
    this.style4ActiveFilterOption = null;
    this.renderFilterTreeHeader();
    this.renderFilterOptionCollapse();
    this.renderFilterOptionClear();
  }

  /**
   * On clicking on mobile button, open the filter tree
   * This function is called by mobile button component
   * @param {Object} event - The onclick event
   */
  onClickMobileButton(event) {
    if (event) {
      event.stopImmediatePropagation();
      event.stopPropagation();
    }

    // Clear the active filter option
    this.style4ActiveFilterOption = null;

    // Set state for mobile button & scroll body
    var $filterTreeElement = jQ(this.idSelector);
    if ($filterTreeElement) {
      this.mobileButton.isCollapsed = !this.mobileButton.isCollapsed;
      if (this.mobileButton.isCollapsed) {
        $filterTreeElement.removeClass(Class.filterTreeMobileOpen);
        jQ('html').removeClass('boost-pfs-body-no-scroll');
        jQ('body').removeClass('boost-pfs-body-no-scroll');
      } else {
        $filterTreeElement.addClass(Class.filterTreeMobileOpen);
        jQ('html').addClass('boost-pfs-body-no-scroll');
        jQ('body').addClass('boost-pfs-body-no-scroll');
      }
    }
    this.mobileButton.afterToggleFilterTree();
  }

  /**
   * Checks condition to see if filter tree is active
   * @param {FilterTreeEnum} filterTreeType - 'vertical' or 'horizontal'
   * @returns {boolean}
   */
  static isActive(filterTreeType) {
    return filterTreeType == FilterTreeEnum.FilterTreeType.VERTICAL
      && Settings.getSettingValue('general.filterTreeMobileStyle') == 'style4';
  }
}

export default FilterTreeStyle4;