/* eslint-disable @lwc/lwc/no-document-query */

const MAX_RETRY = 5;
const TIME_INTERNAL_MS = 500;
const CHAT_BOT_CONTAINER_CLASS = 'genesys-app';
window._userInformation={};// store the logged in user's information
const _USER_INFORMATION_TAGS={"NAME":"NAME","EMAIL":"EMAIL","ACCOUNT_NAME":"ACCOUNT_NAME", "IS_GUEST":"IS_GUEST", "PATH":"PATH"};


let loadGenesysChatbot = function (deploymentId, env) {
(function (g, e, n, es, ys) {
	g['_genesysJs'] = e;
	g[e] = g[e] || function (){
		(g[e].q = g[e].q || []).push(arguments)
	};
	g[e].t = 1 * new Date();
	g[e].c = es;
	ys = document.createElement('script'); ys.async = 1; ys.src = n; ys.charset = 'utf-8'; document.head.appendChild(ys);
	})(window, 'Genesys', 'https://apps.usw2.pure.cloud/genesys-bootstrap/genesys.min.js', {
	environment: env,
	deploymentId: deploymentId
	});

};

		/**Returns the  location tag from the current url*/
		const _getLocationTag = function(url){
			/** Page location sub location */
			let _GET_SUPPORT_PATH = '/s/contactSupport';
			let _SEARCH_RESULT_PATH = '/s/searchresult';
			let  _DEFAULT_TAG = 'Home page'; // we consider unknown value as home page
			const MAP_LOCATION_TAG = {};
			MAP_LOCATION_TAG[_GET_SUPPORT_PATH]='Get Support';
			MAP_LOCATION_TAG[_SEARCH_RESULT_PATH]='Search Page';
	
			
			for(let pathKey in MAP_LOCATION_TAG){
	
				if(url.indexOf(pathKey)>-1){
					return MAP_LOCATION_TAG[pathKey];
				}
			}
	
			return _DEFAULT_TAG;
		}

let _getChatbotComponent = function(){

	let chatbotWrapper = document.getElementsByClassName(CHAT_BOT_CONTAINER_CLASS);
	return chatbotWrapper !== null ?chatbotWrapper[0]:chatbotWrapper;
}

let isChatBotScriptCalled = function(){
	return this._chatbotLoadEventCalled;
}

let _markChatbotCalled = function(){
	this._chatbotLoadEventCalled = true;
}

let hideChatBotHandler = function () {
	let chatBotElement = _getChatbotComponent();
	if (chatBotElement !== undefined) {
	chatBotElement.style.visibility = "hidden";
	} 
}; 

let _chatbotAlreadyLoaded = function () {
	let chatBotElement = _getChatbotComponent();
	if (
	(chatBotElement === undefined || chatBotElement === null) 
	) {
	return false;
	}
	return true; // already loaded check set the display to true
};

let showChatBotHandler = function () {
	let chatBotElement = _getChatbotComponent();

	if (chatBotElement !== undefined && chatBotElement.style !== undefined) {
	chatBotElement.style.visibility = "visible";
	} 
};

let openGenesysChatbot = function(){
	if(window.Genesys !== undefined){
		return window.Genesys('subscribe', 'Messenger.ready', function () {
		window.Genesys('command','Messenger.open');
		});
	}

	return false;
}

//Handler which is triggerd when the chatbot is clicked by the user
const chatBotClickedHandler = function(){
	window.Genesys("command", "Database.set", {
		messaging: {
			customAttributes: {
			source: _getLocationTag(window.location.href),	
			}
		}
		});

}

const chatBotTransferHandler = function(){
    window.Genesys("command", "Database.set", {
        messaging: {
            customAttributes: {
            source: _getLocationTag(window.location.href),
            bot_bot_xfer: true,
            }
        }
    });

}

let bcLoad = function (event) {

	let deploymentId = event.detail.deploymentId;
    let env = event.detail.env;
	// called and the chatbot script has loaded
	if(isChatBotScriptCalled() && _chatbotAlreadyLoaded()){ 
		showChatBotHandler();

		//Attach handlers to trigger callback when chatbot is clicked
		if(window.Genesys !== null && window.Genesys !== undefined ){
			const urlParams = new URLSearchParams(window.location.search);
            const sourceValue = urlParams.get('transfer');
            if (sourceValue === 'dc') {
                window.Genesys("subscribe", "Messenger.opened", chatBotTransferHandler);    
            }
            else{
                window.Genesys("subscribe", "Messenger.opened", chatBotClickedHandler);
            }
		}

	} // called but the script has not loaded // wait for 1 seconds and wait for script to load 
	else if(isChatBotScriptCalled()) {
		this._reloadCounter = this._reloadCounter !== undefined ? this._reloadCounter +1:1;
		
		if(this._reloadCounter < MAX_RETRY){
			// eslint-disable-next-line @lwc/lwc/no-async-operation
		setTimeout(()=>bcLoad(event), TIME_INTERNAL_MS);
		}
		else{
			console.error('Error loading chatbot, maximum retry reached')
		}
		
	}
	else{ // first time loading the chatbot script
		loadGenesysChatbot(deploymentId,env);
		_markChatbotCalled();
	}
	
	};


 // This event is not being sent currently from the chatbot, it will be done later when authenticated experience is needed
	/**Stores the userinformation in the windows object */
	const userInformationHandler = function(event){
		let isGuest = event.detail?.isGuest;
		
		window._userInformation[_USER_INFORMATION_TAGS.PATH] = _getLocationTag(window.location.href);
		window._userInformation[_USER_INFORMATION_TAGS.IS_GUEST] = isGuest;
		if(!isGuest){
			window._userInformation[_USER_INFORMATION_TAGS.NAME] = event.detail?.name;
			window._userInformation[_USER_INFORMATION_TAGS.EMAIL] = event.detail?.email;
			window._userInformation[_USER_INFORMATION_TAGS.ACCOUNT_NAME] = event.detail?.accountId;
			
		}

	}


// end of chatbot script
//Handlers to listen for events triggering the display and hiding of chatbot, the aura component triggers the events which are being executed from the head markup
document.addEventListener("loadChatbotGenesys", bcLoad);
document.addEventListener("hidechatbotGenesys", hideChatBotHandler);
document.addEventListener("openGenesysChatbot", openGenesysChatbot);
document.addEventListener("userInformationGenesys",userInformationHandler);