
//const CT_TL_ENV_ = "";
//2024-01-25
var DEVICE_ID1 = "";
var CT_TL_APP_ID = "TL";
var CT_TL_APP_VERSION =  "";

var MAIN_URL = "https://linebroadcast.com/";
var CT_TL_PARTNER = "openline/tools/tl/v3/tp_tl_customer_v4.js";
var MY_SCRIPT = "openline/tools/tl/v3/";

MAIN_URL = "./";	//for local remark when use remote host
MY_SCRIPT = "myscripts/";	//for local remark when use remote host
CT_TL_PARTNER = "fromhost/tp_tl_customer_v4.js";	//for local remark when use remote host

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

//b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
//b64EncodeUnicode('\n'); // "Cg=="

function b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

//b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
//b64DecodeUnicode('Cg=='); // "\n"

/*
document.addEventListener("DOMContentLoaded",function(event){
	let head = document.querySelector("head");
	let loadJS = function(src){
		let jsLink = document.createElement("script");
		jsLink.src = src ;
		head.appendChild(jsLink);
	};
	console.log("First Javascript file loaded.");
	loadJS("nextFile.js");
});
*/

//Multi Select
/*
<script src="app-assets/js/bootstrap-select.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">  
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>  
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">  
*/

(async function() {
	//await const_init();
	let isLibCompleted = true;
	var scriptNames = [
		"app-assets/vendors/jquery-3.5.1/jquery.js"
		//"app-assets/vendors/jquery-2.2.4/jquery.min.js"
		,"app-assets/js/bootstrap.bundle.min.js"	//required jquery 3.2.1 bootstrap 4.3.1
		,"app-assets/js/bootstrap-multiselect.js"
		,"scripts/sweet.js"
		,"scripts/iziToast.js"
		,"scripts/aes.js"
		//,"scripts/fp.js"
		,"scripts/client.min.js"
		,"app-assets/js/biri/biri.min.js"
		,"app-assets/rome.js"
		,"app-assets/dropdown/msdropdown/js/jquery.dd.js"
		,"app-assets/ce/jquery.csv-0.71.min.js"
		,"app-assets/localStorageDB.js"
		,"app-assets/js/NoSleep.js"
		,"app-assets/js/js.cookie.js"
		,"app-assets/js/jquery-lang.js"
		,"scripts/tp_tl_lang.js"
		,MAIN_URL+CT_TL_PARTNER + "?version=" + (new Date().getTime())
		,"app-assets/w2ui/w2ui-1.5.js"
		,"app-assets/ce/jexcel.js"
		,"app-assets/ce/jquery.jexcel.js"
		,"app-assets/ce/jsuites.js"
		//,"scripts/tp_tl_gfunc.js?version="+ (new Date().getTime())
		,MAIN_URL+MY_SCRIPT + "tp_tl_gfunc.js?version=" //+ (new Date().getTime())
		//,"myscripts/tp_tl_auth.js?version="+ (new Date().getTime())
		,MAIN_URL+MY_SCRIPT + "tp_tl_auth.js?version=" //+ (new Date().getTime())
		//,"scripts/tp_tl_gui.js?version="+ (new Date().getTime())
		,MAIN_URL+MY_SCRIPT + "tp_tl_gui.js?version=" //+ (new Date().getTime())
		,"app-assets/jquery-resizable.js"
		,"app-assets/bootstrap.min.js"
		//,"myscripts/tp_tl_broadcast_line_oa.js?version="+ (new Date().getTime())
		,MAIN_URL+MY_SCRIPT + "tp_tl_broadcast_line_oa.js?version="+ (new Date().getTime())
	];
	
	
	function inject(){
		return new Promise(async (resolve,reject) => {
			for (var i = 0; i < scriptNames.length; i++) {
				let res = await injectScript(scriptNames[i]);
			}
			resolve();
		});
	}
	
	/*
	function inject(){
		return new Promise((resolve,reject) => {
			scriptNames.forEach(async (item) => {
				await injectScript(item);
			});
			resolve();
		});
	}
	*/
	
	function injectScript(src) {
		return new Promise((resolve, reject) => {
			try{
				const script = document.createElement('script');
				script.type = "text/javascript";
				script.charset = "utf-8";
				script.acceptCharset = "utf-8";
				//script.defer = true;
				script.src = src;
				script.async = false; // This is required for synchronous execution
				script.addEventListener('load', resolve(true));
				script.addEventListener('error', e => {
					console.log(e);
					if (isLibCompleted) {
						if(src.indexOf(MAIN_URL)> -1 ){	//show only one time
							isLibCompleted = false;
						}
					}
					resolve(false);
				});
				//script.addEventListener('error', e => reject(e.error));
				
				//console.log(src);
				document.head.appendChild(script);
			}catch(e){
				console.error(e);
				resolve(false);
			}
		});
	}
	
	
	await inject();
	
  // jquery.js and example.js will be run in order and synchronously
	setTimeout(async function() {
		CT_TL_APP_VERSION = await getVersion();
		if(!isLibCompleted){
			Swal.fire({
			  title: "<strong>Unauthorized 403 ("+CT_TL_APP_VERSION+")</strong>",
			  html: '<b>ไม่สามารถเข้าถึงเว็บไซต์เพื่อ Login การใช้งานได้</b><br /> <b>จำเป็นต้องเข้าเว็บไซต์นี้ให้ได้ก่อน</b><br /><b>'+ MAIN_URL +' </b><br /><b><a href="'+MAIN_URL+'" target="_self">คลิ๊กที่นี่</a> หรือ กดปุ่ม OK</b><br />',
			  type: "error",
			  showCancelButton: true,
			  confirmButtonColor: "#3085d6",
			  cancelButtonColor: "#d33",
			  confirmButtonText: "Yes, goto website!"
			}).then((result) => {
			  if (result.isConfirmed) {
				let mywinUrl = window.open(MAIN_URL, '_self');
				mywinUrl.focus();
			  }
			});
		}
	}, 5000);
	
	function sleep(ms) {
		return new Promise(resolve => setTimeout(resolve, ms));
	}

	console.log("Loaded js script finished");
})();

function getClientID() {    //return numeric is success
	return new Promise(resolve =>{
		try {
			var client = new ClientJS(); // Create A New Client Object
			fingerprint = client.getFingerprint(); // Calculate Device/Browser Fingerprint
			if (fingerprint == null) {
				fingerprint = "";
			}
			if (fingerprint == "") {
				var ua = client.getBrowserData().ua;
				var canvasPrint = client.getCanvasPrint();
				fingerprint = client.getCustomFingerprint(ua, canvasPrint);
			}
			if (isNaN(fingerprint)){resolve("");}
			resolve(fingerprint);
		} catch (err) {
			resolve("");
		}
	});
}

function getVersion(){
	return new Promise(resolve =>{
		try{
			var manifestData = chrome.runtime.getManifest();
			//console.log(manifestData.version);
			//console.log(manifestData.default_locale);
			var fst_version_var	= CT_TL_APP_ID+"."+manifestData.version;	//in gfunc.js
			console.log(fst_version_var);
			resolve(fst_version_var);
		}catch(e){}
		resolve("");
	});
}
function initFingerprintJS() {
	// Initialize an agent at application startup.
	return new Promise(resolve =>{
		const fpPromise = FingerprintJS.load()

		// Get the visitor identifier when you need it.
		fpPromise
		  .then(fp => fp.get())
		  .then(result => {
			// This is the visitor identifier:
			const visitorId = result.visitorId
			resolve(visitorId);
		  });
	});
}
/*
async function const_init() {
	CT_TL_APP_VERSION = getVersion();
	DEVICE_ID1 = await getClientID();	//const.js
	console.log(DEVICE_ID1);
	//DEVICE_ID2 = await biri();
	if(DEVICE_ID1==""){
		try{
			chrome.storage.local.get("information", function(info) {
				if(typeof info!=="undefined" && info!=null){
					if(typeof info.information!=="undefined" && info.information!=null){
						if(typeof info.information.device_id!=="undefined" && info.information.device_id!=null){
							if (info.information.device_id) {
								DEVICE_ID1=info.information.device_id.trim();
								console.log(DEVICE_ID1);
							}
						}
					}
				}
				//info && info.information && update_auth_info(info.information, func_call)
			});
		}catch(e){console.log(e);}
	}
}
*/
function const_init_0() {
	return new Promise(async resolve =>{
		CT_TL_APP_VERSION = getVersion();
		//DEVICE_ID1 = await getClientID();	//const.js
		let device_id = await getClientID();	//const.js
		if(DEVICE_ID1==""){
			try{
				//DEVICE_ID1 = await initFingerprintJS();
				if(DEVICE_ID1==""){
					DEVICE_ID1 = device_id;	//const.js
					chrome.storage.local.get("information", async function(info) {
						if(typeof info!=="undefined" && info!=null){
							if(typeof info.information!=="undefined" && info.information!=null){
								if(typeof info.information.device_id!=="undefined" && info.information.device_id!=null){
									if (info.information.device_id) {
										let deviceid = await info.information.device_id;
										if(device_id!=""){
											DEVICE_ID1 = deviceid;
											resolve(DEVICE_ID1);
										}else{
											resolve(DEVICE_ID1);
										}
									}else{
										resolve(DEVICE_ID1);
									}
								}else{
									resolve(DEVICE_ID1);
								}
							}else{
								resolve(DEVICE_ID1);
							}
						}else{
							resolve(DEVICE_ID1);
						}
					});
				}else{
					resolve(DEVICE_ID1);
				}
			}catch(e){
				console.log(e);
				resolve(device_id);
			}
		}else{
			resolve(DEVICE_ID1);
		}
	});
}


function const_init() {
	return new Promise(async resolve =>{
		CT_TL_APP_VERSION = getVersion();
		
		console.log("const_init: ");
		
		let device_id = "";
		try{
			device_id = await initFingerprintJS();
		}catch(e){
			device_id = await getClientID();
		}
		DEVICE_ID1 = device_id;
		console.log("empty device: "+device_id);
		let information_device = {
			device_id:device_id
		}
		try{
			ldb.get('information_device', async function(info) {
				if(typeof info!=="undefined" && info!=null){
					if(typeof info.device_id!=="undefined" && info.device_id!=null){
						device_id = await info.device_id;
						console.log('device:'+DEVICE_ID1);
						if(device_id!=''){
							DEVICE_ID1 = device_id;
							console.log('device:'+DEVICE_ID1);
							information_device = {
								device_id:DEVICE_ID1
							}
							await ldb.set('information_device', information_device);
						}else{
							await ldb.set('information_device', information_device);
						}
						resolve(DEVICE_ID1);
					}else{
						await ldb.set('information_device', information_device);
						resolve(DEVICE_ID1);
					}
				}else{
					await ldb.set('information_device', information_device);
					resolve(DEVICE_ID1);
				}
			});
		}catch(e){
			console.log(e);
			await ldb.set('information_device', information_device);
			resolve(DEVICE_ID1);
		}

	});
}
	
	
	