/**
 * tooltip.js
 * handles tooltip position
 * 
 */

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

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

export class Tooltip {

	constructor(element) {
		this.element = element;
		this.tooltips = [...ElementHelpers.getElementsByAttributeWithinElement(this.element, this.attributes.content)];
		this.setTooltips();
		this.addEventListeners()
	}

	/**
	* Declare attribute constants
	*/
	get attributes() {
		return {
			content: `${attributeBase}-content`,
			pointer: `${attributeBase}-pointer`,
			trigger: `${attributeBase}-trigger`
		}
	}

	addEventListeners() {
		window.addEventListener('load', () => {
			this.setTooltips();
		});
	}

	/**
	* Set tooltips + tooltips pointer
	*/
	setTooltips() {
		this.tooltips.forEach((tooltip) => {
			let tooltipPointer = ElementHelpers.getElementByAttributeWithinElement(tooltip, this.attributes.pointer);
			if (tooltip.parentElement.hasAttribute(this.attributes.trigger)) {
				let tooltipText = tooltip.parentElement;

				// check if tooltip is too far to the right, if so move to the left
				const difference = tooltipText.offsetLeft + tooltip.offsetWidth - this.element.offsetWidth;
				if (difference > 0) {
					tooltip.style.left = `${tooltip.style.left - difference}px`;
					tooltipPointer.style.left = `${(tooltipText.offsetWidth / 2) + Math.abs(difference)}px`;
				}
				else {
					tooltipPointer.style.left = `${tooltipText.offsetWidth / 2 - tooltipPointer.offsetWidth / 2}px`;
				}
			}
		});
	}

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