/**
 * toggable.js
 * toggles class on click or keyup (spacebar)
 * 
 */


/**
* Declare constants
*/
const attributeBase = 'data-rs-toggable';
import Target from './toggable/target';


export class Toggable {

	constructor(element) {
		this.element = element;
		const attributeState = this.element.dataset.rsToggable;
		this.state = Object.values(this.states).indexOf(attributeState) > -1
			? this.element.dataset.rsToggable
			: this.states.inactive;
		this.addEventHandlers();
		this.disableEvents = [];
		this.initialize();
	}

	/**
	* Declare classes
	*/
	get classes() {
		return {
			iconTogglerActive: 'icon__toggler--active'
		}
	}

	/**
	* Declare state constants
	*/
	get states() {
		return {
			active: 'active',
			inactive: 'inactive'
		}
	}

	/**
	 * Initialize toggable elements
	 */
	initialize() {
		this.setClass();
	}

	/**
	 * Add event handlers
	 */
	addEventHandlers() {
		this.element.addEventListener('click', (clickEvent) => {
			clickEvent.preventDefault();
			this.toggleState();
		});
	}

	/**
	 * Toggle current state
	 */
	toggleState() {
		// toggle state
		this.state = this.state === this.states.active
			? this.states.inactive
			: this.states.active;
		this.setClass();
		Target.toggle(this.element, this.state === this.states.active);
	}

	/**
	 * Set the class based on current state
	 */
	setClass() {
		if (this.state === this.states.active) {
			this.element.classList.add(this.classes.iconTogglerActive);
		} else {
			this.element.classList.remove(this.classes.iconTogglerActive);
		}
	}

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