const { ipcMain } = require('electron').remote;
const log = require('electron-log');
const path = require('path');

const contentController = require('./content-controller');
const guide = require('./guide');
const { forMain } = require('../../configs-constants/eventNames.js');

/*const { npm_package_dependencies_neuro_ad: asSubmodule } = process.env;
const srcPrefix = (asSubmodule ? path.join(__dirname, `../../../../../${asSubmodule.substr(5)}/src`) : __dirname);

const mainGuide = require(path.join(srcPrefix, `modules${path.sep}guide${path.sep}js${path.sep}guide.js`));*/

let mainGuide = null; //new mainGuide());
let nad;
let contentContainer;
const STATE = Object.freeze({
	fullscreen: 'fullscreen',
	minimize: 'minimize',
	hidden: 'hidden',
	disabled: 'disabled',
});
let currentState = STATE.disabled;
const alertTime = 1000 * 5;
let closeTakeWithMeErrorTimeout = setTimeout(() => {}, 0);
let closeTakeWithMeErrorDelay = 1000 * 5;

const setInitEvent = () => {
	try {
		ipcMain.once(forMain.pageReady, init);
		// init();
	} catch (e) {
		log.error(e);
	}
};

const init = () => {
	try {
		mainGuide = g_guide;
	} catch (e) {
		log.warn('main guide not initialized on neuroAd');
	}

	try {
		nad = document.body.querySelector('.neuroad');
		contentContainer = nad.querySelector('.content-container');

		switchStateTo(STATE.minimize);

		document.addEventListener('common-full_reset', () => switchStateTo(STATE.fullscreen));
		// document.addEventListener('pointerdown', _eventPointerDownBody, false);
		document.addEventListener('route_change', handleRouteChange);

		// ipcRenerer.send
	} catch (e) {
		log.error(e);
	}
};
const switchStateTo = (newState) => {
	try {
		if (!newState) {
			log.warn('neuroAd new state undefined');

			return false;
		} else if (newState === currentState) {
			return false;
		}

		switch (currentState) {
			case STATE.fullscreen:
				fromFullscreen();
				break;
			case STATE.minimize:
				fromMinimize();
				break;
			case STATE.hidden:
				fromHidden();
				break;
			case STATE.disabled:
				fromDisable();
				break;
			default:
				log.warn('neuroAd current state unexpected');
				return false;
		}

		setTimeout(() => {
			switch (newState) {
				case STATE.fullscreen:
					toFullscreen();
					break;
				case STATE.minimize:
					toMinimize();
					break;
				case STATE.hidden:
					toHidden();
					break;
				case STATE.disabled:
					toDisable();
					break;
				default:
					log.warn('neuroAd new state unexpected');
					return false;
			}

			currentState = newState;
		}, 0);
	} catch (e) {
		log.error(e);
	}
};
/* Fullscreen */
const toFullscreen = () => {
	try {
		unmute();
		guide.autoplay();
		mainGuide?.mute(true);
		nad.classList.add('neuroad_fullscreen');
		document.body.classList.add('n-ad-fullscreen');
		document.dispatchEvent(new CustomEvent('neuro-ad-open'));

		nad.addEventListener('pointerdown', _eventPointerDownFullscreen, true);
	} catch (e) {
		log.error(e);
	}
};
const fromFullscreen = () => {
	try {
		guide.destroy();
		nad.classList.remove('neuroad_fullscreen');
		document.body.classList.remove('n-ad-fullscreen');
		document.dispatchEvent(new CustomEvent('neuro-ad-close'));
		nad.removeEventListener('pointerdown', _eventPointerDownFullscreen, true);

		if(typeof window === 'object' && typeof window.adGuidePlayIntroInfo === 'object' &&
			window.adGuidePlayIntroInfo.enable && typeof window.adGuidePlayIntroInfo.timeoutInterval === 'number') {

			setTimeout(() => {
				mainGuide?.mute(false);

				if (document.body.classList.contains('map_showing')) return;

				mainGuide?.playPath(['intro'], {
					callback: () => { if(document) document.dispatchEvent(new CustomEvent("neuro-ad-played_intro")) },
					maximize_before: false,
					minimize_after: false,
				});
			}, window.adGuidePlayIntroInfo.timeoutInterval);
		}
	} catch (e) {
		log.error(e);
	}
};
const _eventPointerDownFullscreen = () => {
	try {
		switchStateTo(STATE.minimize);
	} catch (e) {
		log.error(e);
	}
};
/* Minimize */
const toMinimize = () => {
	try {
		mute();
		addButtonsEvents();
		nad.classList.add('neuroad_minimize');
		contentContainer.addEventListener('pointerdown', _eventPointerDownMinimized, true);
	} catch (e) {
		log.error(e);
	}
};
const fromMinimize = () => {
	try {
		removeButtonsEvents();
		nad.classList.remove('neuroad_minimize');
		contentContainer.removeEventListener('pointerdown', _eventPointerDownMinimized, true);
	} catch (e) {
		log.error(e);
	}
};
const _eventPointerDownMinimized = () => {
	try {
		switchStateTo(STATE.fullscreen);
	} catch (e) {
		log.error(e);
	}
};
/* Hidden */
const toHidden = () => {
	try {
		mute();
		nad.classList.add('neuroad_hidden');
		nad.addEventListener('pointerdown', _eventForHidden, true);
	} catch (e) {
		log.error(e);
	}
};
const fromHidden = () => {
	try {
		nad.classList.remove('neuroad_hidden');
		nad.removeEventListener('pointerdown', _eventForHidden, true);
	} catch (e) {
		log.error(e);
	}
};
const _eventForHidden = () => {
	try {
		switchStateTo(STATE.minimize);
	} catch (e) {
		log.error(e);
	}
};
/* Disabled */
const toDisable = () => {
	try {
		mute();
		nad.classList.add('neuroad_disabled');
	} catch (e) {
		log.error(e);
	}
};
const fromDisable = () => {
	try {
		nad.classList.remove('neuroad_disabled');
	} catch (e) {
		log.error(e);
	}
};
/* click body */
let handleRouteChange = function(event) {
	/*if ( findParentByClasses(event.target, 'neuroad') ) {
        return false;
    }*/
	let route = event.detail.route,
		way = event.detail.way;
	if (route === 'start') {
		if (way === 'enter') {
			switchStateTo(STATE.hidden);
		} else {
			setTimeout(() => {
				switchStateTo(STATE.disabled);
			}, 0);
		}
	}
};
const _eventPointerDownBody = (event) => {
	try {
		if (findParentByClasses(event.target, 'neuroad')) {
			return false;
		}

		setTimeout(() => {
			const body = document.body;

			if (
				body.classList.contains('map_showing') ||
				body.classList.contains('search_extended') ||
				body.classList.contains('rita-fullscreen') ||
				body.classList.contains('guide_brand_showing') ||
				body.classList.contains('mobile_opened') ||
				body.classList.contains('call_center_showing')
			) {
				switchStateTo(STATE.disabled);
			} else {
				switchStateTo(STATE.hidden);
			}
		}, 0);
	} catch (e) {
		log.error(e);
	}
};
/* helpers */
const findParentByClasses = (elem, selectors) => {
	try {
		const classesArr = selectors.split(' ');
		let result = null;
		let currentElem = elem;

		while (true) {
			for (let i = 0; i < classesArr.length; i++) {
				if (currentElem.classList.contains(classesArr[i])) {
					result = currentElem;

					break;
				}
			}

			if (result) {
				break;
			} else if (currentElem.parentElement) {
				currentElem = currentElem.parentElement;
			} else {
				break;
			}
		}

		return result;
	} catch (e) {
		log.error(e);
	}
};
/* Buttons */
const addButtonsEvents = () => {
	try {
		nad.querySelectorAll('.js-neuroad-btn').forEach((btn) => {
			btn.addEventListener('pointerdown', _eventButtonPointerDown, true);
		});
	} catch (e) {
		log.error(e);
	}
};
const removeButtonsEvents = () => {
	try {
		nad.querySelectorAll('.js-neuroad-btn').forEach((btn) => {
			btn.removeEventListener('pointerdown', _eventButtonPointerDown, true);
		});
	} catch (e) {
		log.error(e);
	}
};
const _eventButtonPointerDown = (event) => {
	try {
		const btn = event.currentTarget;

		if (btn.classList.contains('neuroad-btn-close')) {
			switchStateTo(STATE.hidden);
		} else if (btn.classList.contains('neuroad-btn_mobile')) {
			const link = contentController.getLinkForPlayingContent();

			if (!link) {
				const offsetTop = btn.offsetTop + btn.offsetParent.offsetTop;

				takeWithMeError();

				return false;
			}

			window.takeMobile.show('neuroad');
			window.takeMobile.saveLinkToAd(link);
		} else if (btn.classList.contains('neuroad-btn_mute')) {
			mute();
		} else if (btn.classList.contains('neuroad-btn_unmute')) {
			unmute();
		}
	} catch (e) {
		log.error(e);
	}
};
const mute = () => {
	try {
		const muteBtn = nad.querySelector('.neuroad-btn_mute');

		if (muteBtn) {
			muteBtn.classList.remove('neuroad-btn_mute');
			muteBtn.classList.add('neuroad-btn_unmute');
		}

		contentController.setMute(true);
	} catch (e) {
		log.error(e);
	}
};
const unmute = () => {
	try {
		const muteBtn = nad.querySelector('.neuroad-btn_unmute');

		if (muteBtn) {
			muteBtn.classList.remove('neuroad-btn_unmute');
			muteBtn.classList.add('neuroad-btn_mute');
		}

		contentController.setMute(false);
	} catch (e) {
		log.error(e);
	}
};

const alert = (text, offsetTop) => {
	try {
		if (!text) {
			return log.warn('mod:indoor-nav-helper/alert()', "don't send text for alert");
		}

		let elem = document.createElement('div');
		elem.classList.add('neuroad-alert');
		elem.innerHTML = text;

		if (offsetTop) {
			elem.style.top = parseInt(offsetTop, 10) + 'px';
		}

		elem = nad.appendChild(elem);

		elem.classList.add('neuroad-alert_show');

		setTimeout(() => elem.remove(), alertTime);
	} catch (e) {
		log.error(e);
	}
};

const takeWithMeError = () => {
	try {
		const errorElem = nad.querySelector('.take-with-me-error');

		if (!errorElem) return false;

		if (errorElem.classList.contains('take-with-me-error_showed')) {
			clearTimeout(closeTakeWithMeErrorTimeout);

			errorElem.animate(
				[{ transform: 'scale3d(1,1,1)' }, { transform: 'scale3d(1.1,1.1,1)' }, { transform: 'scale3d(1,1,1)' }],
				{
					duration: 300,
					iterations: 1,
				},
			);
		}

		errorElem.classList.add('take-with-me-error_showed');

		closeTakeWithMeErrorTimeout = setTimeout(() => {
			errorElem.classList.remove('take-with-me-error_showed');
		}, closeTakeWithMeErrorDelay);
	} catch (e) {
		log.error('NAD:indoor-nav-helper takeWithMeError() broken', e);
	}
};

window.adSwitchStateTo = switchStateTo;
window.adGuidePlayIntroInfo = {
	enable: true,
	timeoutInterval: 1000
};
module.exports = setInitEvent();
