/**
 * video.js
 * 
 */

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

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

export class Video {

	constructor(element) {
		this.element = element;
		this.modal = ElementHelpers.getElementByAttribute(this.attributes.modal, this.element.getAttribute(attributeBase));
		this.iframe = ElementHelpers.getElementByAttribute(this.attributes.iframe, this.element.getAttribute(attributeBase));
		this.scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
		this.scrollPosition = 0;
		this.bodyMarginTop = this.initializeBodyMarginTop();
		this.addEventHandlers();
	}

	/**
	* Declare classes
	*/
	get classes() {
		return {
			modal: 'modal',
			modalActive: 'modal--active',
			modalOpen: 'modal-open',
			modalOverlayActive: 'modal__overlay--active'
		}
	}

	/**
	* Declare attribute constants
	*/
	get attributes() {
		return {
			overlay: `${attributeBase}-overlay`,
			modal: `${attributeBase}-modal`,
			iframe: `${attributeBase}-iframe`
		}
	}

	/**
	* Initalize body margin top
    */
	initializeBodyMarginTop() {
		if (document.body.style.marginTop === '' ||
			document.body.style.marginTop === null) {
			return 0;
		}
		else {
			return document.body.style.marginTop.slice(0, document.body.style.marginTop.length - 2);
		}
	}

	/**
	 * Add event handlers
	 */
	addEventHandlers() {
		this.element.addEventListener('click', (event) => {
			event.preventDefault();
			this.scrollPosition = window.pageYOffset;
			this.toggleModal();
		});
		this.modal.addEventListener('click', (event) => {
			event.preventDefault();
			this.toggleModal();
			document.body.style.marginTop = `${this.bodyMarginTop}px`;
			window.scrollTo(0, this.scrollPosition);
		});
	}

	/**
	 * Toggle modal
	 */
	toggleModal() {
		if (this.modal.classList.contains(this.classes.modalActive)) {
			// stop playing video
			this.iframe.setAttribute('src', this.iframe.getAttribute('src'));

			// remove width of scrollbar to body and modal
			document.body.style.paddingRight = '0px';
			this.modal.style.paddingRight = '';
		}
		else {
			document.body.style.marginTop = `${(this.bodyMarginTop - this.scrollPosition)}px`;
			// set padding right to width of scrollbar
			document.body.style.paddingRight = `${this.scrollbarWidth}px`;
			this.modal.style.paddingRight = `${this.scrollbarWidth}px`;
		}
		document.querySelector('html').classList.toggle(this.classes.modalOpen);
		this.modal.classList.toggle(this.classes.modalActive);
	}

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