/**
 * popover.js
 */

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

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

export class Popover {

	constructor(element) {
		this.element = element;
		this.trigger = ElementHelpers.getElementByAttribute(this.attributes.trigger, this.element.getAttribute(attributeBase));
		this.overlay = ElementHelpers.getElementByAttribute(this.attributes.overlay);
		this.disableOverlay = this.element.hasAttribute(this.attributes.disableOverlay);
		this.addEventHandlers();
	}

	/**
	* Declare classes
	*/
	get classes() {
		return {
			popoverActive: 'popover--active',
			modalOverlayActive: 'modal__overlay--active',
			active: 'active'
		}
	}

	/**
	* Declare attribute constants
	*/
	get attributes() {
		return {
			overlay: `${attributeBase}-overlay`,
			trigger: `${attributeBase}-trigger`,
			disableOverlay: `${attributeBase}-disable-overlay`
		}
	}

	/**
	 * Add event handlers
	 */
	addEventHandlers() {
		if (this.trigger !== null) {
			this.trigger.addEventListener('click', () => {
				if (this.element.classList.contains(this.classes.popoverActive)) {
					this.element.classList.remove(this.classes.popoverActive);
					if (this.overlay !== null && !this.disableOverlay) {
						this.overlay.classList.remove(this.classes.modalOverlayActive);
					}
				}
				else {
					this.element.classList.add(this.classes.popoverActive);
					if (this.overlay !== null && !this.disableOverlay) {
						this.overlay.classList.add(this.classes.modalOverlayActive);
					}
				}
				this.toggleActiveClassOnTrigger();
			});
		}
		if (this.overlay !== null && !this.disableOverlay) {
			this.overlay.addEventListener('click', () => {
				this.element.classList.remove(this.classes.popoverActive);
				this.overlay.classList.remove(this.classes.modalOverlayActive);
				this.toggleActiveClassOnTrigger();
			});
		}
		else {
			window.addEventListener('click', (clickEvent) => {
				if (!this.trigger.contains(clickEvent.target)
					&& this.element.classList.contains(this.classes.popoverActive)
					&& !this.element.contains(clickEvent.target)) {
					this.element.classList.remove(this.classes.popoverActive);
				}
				this.toggleActiveClassOnTrigger();
			});
		}
	}

	/**
	 * Toggle active class on trigger element
	 */
	toggleActiveClassOnTrigger() {
		if (this.trigger.classList.contains(this.classes.active)) {
			this.trigger.classList.remove(this.classes.active);
		} else {
			this.trigger.classList.add(this.classes.active);
		}
	}

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