// JavaScript Document


var audio = document.createElement("audio");;
var audioCont = document.getElementById("audioCont");
function stopAudio(){	
	audio.pause();
	audio.currentTime = 0;
	audio.removeAttribute("controls", "controls");
	
	//audioCont.style.pointerEvents = "auto";
	//audioCont.style.opacity = 1;
}

var scorm, LMSdata, isFirstAttempt=true;
var CURRENT_PAGES;
var scorm;

window.addEventListener("load", e=>{

	function bindEvent(element, eventName, eventHandler) {
		if (element.addEventListener) {
			element.addEventListener(eventName, eventHandler, false);
		} else if (element.attachEvent) {
			element.attachEvent('on' + eventName, eventHandler);
		}
	}
	
	bindEvent(window, 'message', function (e) {
		//console.log("messgae: ", e.data);
		window[e.data.fun](e.data.arg, true)
		
	});
	scorm = pipwerks.SCORM;	

	waitForLMSConnection();
	
})

window.addEventListener("unload", e=>{
	LMSset("cmi.suspend_data", LMSdata);
})

/* function saveData(){
	console.log("SAVING DATA ON BLUR.........");
	LMSset("cmi.suspend_data", LMSdata);
} */
function saveData(_data, _saveLMS){		
	console.log("Save Data: ", _data, _saveLMS);
	let key = Object.keys(_data)[0];
	LMSdata[key] = _data[key];
	if(_saveLMS){
		console.log("LMS DATA: ", LMSdata);
		LMSset("cmi.suspend_data", LMSdata);
	}

	if(allArrayFilled(LMSdata)){
		console.log("Final");	
		LMSset("cmi.core.lesson_status", "completed");
		console.log("Final2");
	}

	
}

// function allArrayFilled(obj) {
// 	for (let key in obj) {
// 	  if (Array.isArray(obj[key])) {
// 		// Check if the array is effectively empty (including arrays of null values)
// 		const hasNonNullElement = obj[key].some(
// 		  (element) => element !== null
// 		);
// 		if (obj[key].length === 0 || !hasNonNullElement) {
// 		  return false; // Found an empty or effectively empty array
// 		}
// 	  }
// 	}
// 	return true;
//   }
function allArrayFilled(obj) {
	for (let key in obj) {
		if (key === "p_5") continue; // Skip p_5 key

		if (Array.isArray(obj[key])) {
			const array = obj[key];

			// Check if the array is empty or only contains null/undefined
			const hasValidValue = array.some(
				element => element !== null && element !== undefined
			);

			if (array.length === 0 || !hasValidValue) {
				return false;
			}
		}
	}
	return true;
}

function connectToLMS() {
	return new Promise((resolve, reject) => {
	  scorm = pipwerks.SCORM; // Shortcut to the SCORM API
	  const success = scorm.init(); // Attempt to initialize SCORM connection
	  // Resolve or reject the promise based on the success of the connection
	  if (success) {
		console.log("Connection to LMS established successfully.");
		let status = LMSget("cmi.core.lesson_status");
		console.log(status);
		
		resolve(true);
	  } else {
		console.log("Failed to connect to LMS.");
		//reject(new Error("Failed to connect to LMS."));
		let status = LMSget("cmi.core.lesson_status");
		console.log("----------",status);
		if(status == "completed"){
		  isFirstAttempt = false;
		}
		let susData = LMSget("cmi.suspend_data");
		console.log("SUS DATA: ", susData, "TYPE: ", typeof susData);
		LMSdata = (susData =='undefined' || susData == 'null' || !susData) ?getLMSData():JSON.parse(susData);
		console.log("LMS DATA: ", LMSdata);		
		setTurn("1-2");
	  }
	});
  }

  async function waitForLMSConnection() {
	try {
	  // Await for the connection promise to resolve
	  await connectToLMS();
	  console.log("Now connected to LMS, you can proceed with SCORM operations.");
	  
	  let susData = LMSget("cmi.suspend_data");
	  //console.log("SUS DATA: ", susData, "TYPE: ", typeof susData);
	  LMSdata = (susData=='undefined' || susData == 'null' || !susData) ?getLMSData():JSON.parse(susData);
	  setTurn("1-2");
	  // Proceed with your SCORM operations here
	} catch (error) {
	  // Handle the error in case of connection failure
	  console.log("Error connecting to LMS:", error.message);
	  setTurn("1-2");
	}

  }

  function getLMSData(){
	let data={};
	$(".ifrm").each((id, item)=>{
		data["p_"+(id+1)] = [];
	})
	return data;
  }

function LMSget(key) {
	let val = null;
	if(!isFirstAttempt){
		  return val;
	  }
	//return localStorage.getItem(key);
	try {
	  val = scorm.get(key);
	} catch (err) {
	  console.log("LMS GET ERROR: ", val);
	}
	//console.log("LMS GET ", key, val);
	return val;
}
function LMSset(key, value) {
	if(!isFirstAttempt){
		  return;
	  }
	//localStorage.setItem(key, JSON.stringify(value)); 
	try {	  
	//   value = JSON.stringify(value);
	if (key === "cmi.suspend_data") {
			value = JSON.stringify(value);
		}

	  //console.log("LMS SET: ", key, value);  
	  scorm.set(key, value);
	  scorm.save();
	} catch (err) {
	  console.log("LMS SET ERROR: ", err);
	}

}

//Code updated by Inder................................
function setTurn(_pages){
	CURRENT_PAGES = _pages.split("-")
	console.log("CURRENT_PAGES", CURRENT_PAGES);
	CURRENT_PAGES.forEach((page, id) => {
		page = page.trim();
		console.log("page: ", page, "  id", id, "frame-"+page);
		console.log("LMSdata: ", LMSdata);
		console.log("=======", document.getElementById("frame-" + page));
		
		try {
			if(LMSdata  && Object.keys(LMSdata).length)
			{
            	document.getElementById("frame-" + page).contentWindow.postMessage({ "fun": "startIntro", "arg": LMSdata["p_"+page] }, "*");
			}else{
				document.getElementById("frame-" + page).contentWindow.postMessage({ "fun": "startIntro", "arg": [] }, "*");
			}
        } catch (err) {
            console.log(err);
        }
	});
}
//Code updated by Inder................................Ends

window.addEventListener('beforeunload', function(event) {
console.log("unloading.......");
LMSset("cmi.suspend_data", LMSdata);

});