/**
 * filter.js
 * Handles all filer functionality
 */

import ElementHelpers from '../helpers/element-helpers';

/**
* Declare constants
*/
const attributeBase = 'data-rs-filter';

export class Filter {

	constructor(element) {
		this.element = element;
		this.refineSearchButton = ElementHelpers.getElementByAttributeWithinElement(this.element, this.attributes.refineSearch);
		this.filterContent = ElementHelpers.getElementByAttributeWithinElement(this.element, this.attributes.content);
		this.filterClose = ElementHelpers.getElementByAttributeWithinElement(this.element, this.attributes.close);
		this.scrollPosition = 3;
		this.addEventHandlers();
	}

	/**
	* Declare attribute constants
	*/
	get attributes() {
		return {
			refineSearch: `${attributeBase}-refine-search`,
			content: `${attributeBase}-content`,
			close: `${attributeBase}-close`
		}
	}

	/**
	* Declare classes
	*/
	get classes() {
		return {
			active: 'filter__content--active',
			scrollActive: 'scroll-active',
			filterActive: 'filter-active'
		}
	}

	/**
	 * Add event handlers
	 */
	addEventHandlers() {
		this.refineSearchButton.addEventListener('click', () => {
			this.filterContent.classList.add(this.classes.active);
			document.body.classList.add(this.classes.filterActive);
		});
		this.filterClose.addEventListener('click', () => {
			this.filterContent.classList.remove(this.classes.active);
			document.body.classList.remove(this.classes.filterActive);
		});
		this.filterContent.addEventListener('scroll',  () => {
			this.checkPosition();
		})
	}

	/**
	 * Check position
	 */
	checkPosition() {
		const modalMainY = this.filterContent.scrollTop;
		if (this.filterContent && modalMainY > this.scrollPosition) {
			this.filterContent.classList.add(this.classes.scrollActive);
		}
		if (this.filterContent && modalMainY < this.scrollPosition || this.filterContent && modalMainY === 0 ) {
			this.filterContent.classList.remove(this.classes.scrollActive);
		}
	}

	/**
	 * Get selector
	 */
	static getSelector() {
		return `[${attributeBase}]`;
	}
}
