//global variable------------------------------------------------

"use strict";

const DEBUG = true;


function stric(obj) {
    try {
	
        return stricSafe(obj);
    } catch(e) {
        console.error("Stric failed:", e.stack);
        throw e;
    }
}
function stricSafe(obj) {
    if (!DEBUG) return obj;

    return new Proxy(obj, {
        get(target, prop) {
            if (!(prop in target) &&
                typeof prop !== "symbol" &&
                !["toJSON"].includes(prop)) {
                throw new Error("Property '" + prop + "' does not exist in " + target.constructor.name);
            }
            return target[prop];
        },
        set(target, prop, value) {
            if (!(prop in target)) {
                throw new Error("Cannot add new property '" + prop + "' to " + target.constructor.name);
            }
            target[prop] = value;
            return true;
        },
        deleteProperty(target, prop) {
            throw new Error("Cannot delete property '" + prop + "' from " + target.constructor.name);
        },
        defineProperty(target, prop, descriptor) {
            if (!(prop in target)) {
                throw new Error("Cannot define new property '" + prop + "' on " + target.constructor.name);
            }
            return Reflect.defineProperty(target, prop, descriptor);
        },
        setPrototypeOf(target, proto) {
            throw new Error("Cannot change prototype of " + target.constructor.name);
        },
        has(target, prop) {
            if (!(prop in target)) {
                throw new Error("Property '" + prop + "' does not exist in " + target.constructor.name);
            }
            return true;
        }
    });
}



function cloneStrict(ClassType, source, options) {
    options = options || {};
    var DEBUG = (options.DEBUG !== undefined) ? options.DEBUG : true;

    // 1?? Create new class instance
    var temp = new ClassType();

    // 2?? Copy data from source (shallow copy)
    if (source && typeof source === "object") {
        Object.assign(temp, source);
    }

    // 3?? If not DEBUG, return normally
    if (!DEBUG) return temp;

    // 4?? Avoid Proxy for null, primitives, or DOM elements
    if (temp === null || typeof temp !== "object") return temp;
    if (typeof HTMLElement !== "undefined" && temp instanceof HTMLElement) return temp;
    if (typeof Image !== "undefined" && temp instanceof Image) return temp;

    // 5?? Apply strict Proxy
    return new Proxy(temp, {
        get: function(target, prop) {
            if (!Object.prototype.hasOwnProperty.call(target, prop) &&
                typeof prop !== "symbol" &&
                !["toJSON"].includes(prop)) {
                throw new Error(
                    "Property '" + prop + "' does not exist in " + target.constructor.name
                );
            }
            return target[prop];
        },
        set: function(target, prop, value) {
            if (!Object.prototype.hasOwnProperty.call(target, prop)) {
                throw new Error(
                    "Cannot add new property '" + prop + "' to " + target.constructor.name
                );
            }
            target[prop] = value;
            return true;
        },
        deleteProperty: function(target, prop) {
            throw new Error(
                "Cannot delete property '" + prop + "' from " + target.constructor.name
            );
        },
        defineProperty: function(target, prop, descriptor) {
            if (!Object.prototype.hasOwnProperty.call(target, prop)) {
                throw new Error(
                    "Cannot define new property '" + prop + "' on " + target.constructor.name
                );
            }
            return Reflect.defineProperty(target, prop, descriptor);
        },
        setPrototypeOf: function(target, proto) {
            throw new Error(
                "Cannot change prototype of " + target.constructor.name
            );
        },
        has: function(target, prop) {
            if (!Object.prototype.hasOwnProperty.call(target, prop)) {
                throw new Error(
                    "Property '" + prop + "' does not exist in " + target.constructor.name
                );
            }
            return true;
        }
    });
}




let G1the			 = null;
let G2the			 = null;
let G3the			 = null;
let theLoginCls		 = null;

let theRotation=0;
let theX	=0;
let theY	=0;
let theWid	=1024;
let theHed	=576;
let theActivePage=0;

let theWebSocket = null		  ;
let theGameList=[];
let thePrTimerID=0;

let thePara1="";
let thePara2="";

let theSockDiscon=0;
let theTryToConnect=0;
let theUnlockAudio=0;
let theIsLoadingAllImage_Called=0;

// Include Many js files-----------------------------------------
function include(file, next)
{
    var script = document.createElement("script");

    script.src   = file;
    script.type  = "text/javascript";
    script.async = false;              //to make order of include keep(js funcs is not async,but download js file is aysnc)

    script.onload = function ()
    {
        console.log(file + " loaded");
        if (next) next();
    };

    script.onerror = function ()
    {
        console.error("FAILED: " + file);
    };

    document.head.appendChild(script);
}



//(some web loading timing problem,sometimes not defined function happen,so at the sametime with web.html)


function base64Encodemulti(str) 
{
    // Convert the string to a Uint8Array (UTF-8 encoded bytes)
    const utf8Bytes = stric(new TextEncoder().encode(str));

    // Convert the bytes to Base64
    let base64String = '';
    for (let i = 0; i < utf8Bytes.length; i++) {
        base64String += String.fromCharCode(utf8Bytes[i]);
    }

    return btoa(base64String); // Base64 encode the string
}

function base64Decodemulti(base64Str) 
{
    // Decode the Base64 string
    const decodedString = atob(base64Str);

    // Convert the Base64 decoded string back to bytes (Uint8Array)
    const utf8Bytes = stric(new Uint8Array(decodedString.length));
    for (let i = 0; i < decodedString.length; i++) {
        utf8Bytes[i] = decodedString.charCodeAt(i);
    }

    // Convert the bytes back to a UTF-8 string
    return stric(new TextDecoder().decode(utf8Bytes));
}
//only ascii encode available maybe
function base64Encode(str) {
    return btoa(str); // Simply use btoa() to encode/ascii only
}
function base64Decode(str) {
    return atob(str); // Simply use atob() to decode,ascii only
}

function condisplay(str) 
{
	console.log(str);
}


function resizeAndCenterPopup(wid,hed) {
 // Calculate the window chrome (borders, title bar)
    const dw = window.outerWidth - window.innerWidth;
    const dh = window.outerHeight - window.innerHeight;

    // Resize window to make client area exact
    window.resizeTo(wid + dw, hed + dh);

    // Center on screen using screen.availWidth / screen.availHeight
    const left = (screen.availWidth - window.outerWidth) / 2;
    const top  = (screen.availHeight - window.outerHeight) / 2;

    // Move the window
    window.moveTo(left, top);
	

    //console.log('Client width:', window.innerWidth);
    //console.log('Client height:', window.innerHeight);
    //console.log('Outer width:', window.outerWidth);
    //console.log('Outer height:', window.outerHeight);
}

function resizeAndCenterPopup_reliable(wid, hed) {
    // First resize attempt
    window.resizeTo(
        wid + (window.outerWidth - window.innerWidth),
        hed + (window.outerHeight - window.innerHeight)
    );

    // Let browser finish resizing
    setTimeout(() => {
        // Recalculate delta AFTER resize
        const dw = window.outerWidth - window.innerWidth;
        const dh = window.outerHeight - window.innerHeight;

        // Correct height drift
        window.resizeTo(wid + dw, hed + dh);

        // Center
        const left = Math.round((screen.availWidth  - window.outerWidth)  / 2);
        const top  = Math.round((screen.availHeight - window.outerHeight) / 2);
        window.moveTo(left, top);
    }, 0);
}



function onLoadWebPage()//(only once called when all-images is all-loaded)
{
	//resizeAndCenterPopup(GAME_X,GAME_Y);
	//resizeAndCenterPopup_reliable(GAME_X,GAME_Y);
	
	//geting id,pw------------------------------------------------------------------------
	/*
	const params = window.location.href;

	let startIndex = params.indexOf("para1=") + "para1=".length; 
	let endIndex = params.indexOf("&", startIndex);if(endIndex==-1) endIndex = params.length; 
	
	if(startIndex==-1 || endIndex==-1) return;

	thePara1 = params.substring(startIndex, endIndex);

	startIndex = params.indexOf("para2=") + "para1=".length;
	endIndex = params.indexOf("&", startIndex);if(endIndex==-1) endIndex = params.length;
	
	if(startIndex==-1 || endIndex==-1) return;

	thePara2 = params.substring(startIndex, endIndex); // Extract the value of para1


	thePara1 =base64Decode(thePara1);
	thePara2 =base64Decode(thePara2);
	*/
	//geting id,pw------------------------------------------------------------------------

	the_OnLoad_ALL_AddEventPage();

	return;
}

function the_OnLoad_ALL_AddEventPage()
{

}

function writeIntToScreen(para)
{
	//document.getElementById("display1").innerText=para.toString();
}

function B_moveEditCtrl(conid,left,top,width,height)
{
	width=width*theWid/1920;height=height*theWid/1920;
	left=left*theWid/1920+theX;top= top*theWid/1920+theY;
	
	let edit  = document.getElementById(conid);

	edit.style.resize ="none";
	edit.style.textdecoration="none";
	edit.style.fontSize="11px";
	edit.style.border="0";


	edit.style.position  = "absolute";
	edit.style.left		 = Math.round(left).toString()  +"px";
	edit.style.top		 = Math.round(top).toString()   +"px";
	edit.style.width	 = Math.round(width).toString() +"px";
	edit.style.height	 = Math.round(height).toString()+"px";

	let dx=width -edit.offsetWidth  ;
	let dy=height-edit.offsetHeight ;

	dx+=width ;let dxp= dx.toString()+"px";
	dy+=height;let dyp= dy.toString()+"px";

	edit.style.width  =dxp;
	edit.style.height =dyp;
	
	edit.style.color= "#9b9f96"; 
	//edit.style.backgroundColor="#172532";
}

let theWayOfRotation=0;//0->body rotation,1->container rotation
let theContainerRotateDone=0;
let theBodyRotationDone=0;

function Body_moveCtrl()
{
	if(theWayOfRotation==0) return;
	
	let w = window.innerWidth;
	let h = window.innerHeight;

	let left=0,top=0,wid=0,hed=0;

	if(theRotation==1)
	{
		if(theBodyRotationDone==0)
		{
			theBodyRotationDone=1;
			document.body.style.transform = "rotate(90deg)";
			document.body.style.transformOrigin = "center center";
		}
	}
	else
	{
		if(theBodyRotationDone==1   ){
			theBodyRotationDone=0   ; document.body.style.transform = "none";
		}
	}
	//console.log("document" ,document.body.style.left, document.body.style.top,document.body.style.width,document.body.style.height);
}

function B_moveCtrl(conid,left,top,width,height,canvas=0,querybuttype=0)
{
	document.body

	let con=null;
	if(typeof conid === "string"){
		 con  = document.getElementById(conid );
		 //if(!con) {alert("conid invalid:"+conid);return;}
		 if(!con) {return;}
	}
	else{
		con=conid;
	}
	
	if(theRotation==1)
	{
		let w = window.innerWidth;
		let h = window.innerHeight;

		if(canvas!=0)
		{
			if(conid=="gamecontainer1")
			{
				if(theContainerRotateDone==0 ){
					theContainerRotateDone=1;
					con.style.transform = "rotate(90deg)";
					con.style.transformOrigin = "center center";
				}
				
				let sh=(theWid-theHed)/2 + (h-theWid)/4;//(h-theWid)/2
				top+=sh;
				let sw=(w-(theX+theWid))/2;
				left=sw;//(theHed-theWid)/2 + (w-theHed)/2 -sh/2 ;
			}
			
			//console.log(con.style.left,con.style.top,con.style.width,con.style.height,left,top,width,height);
			
			B_moveCtrl_c(con,left,top,width,height,canvas);
			
		}
		else{
			B_moveCtrl_c(con,left,top,width,height,canvas);
		}
	}
	else
	{
		if(conid=="gamecontainer1" ) {
			if(theContainerRotateDone==1){theContainerRotateDone=0; con.style.transform = "none";}
			//console.log("container",con.style.left, con.style.top,con.style.width,con.style.height);
		}
	
		B_moveCtrl_c(con,left,top,width,height,canvas);
	}
}

function B_moveCtrl_c(con,left,top,wid,hed,canvas)
{
	if(canvas!=0){
		left+=theX/2;
		//console.log("after"+con.style.left,con.style.top,con.style.width,con.style.height,left,top,wid,hed);
	}
	else{
		wid*=theWid/1920;hed*=theWid/1920;
		left= (left)*theWid/1920+theX/2;top= (top)*theWid/1920+theY;
	}
	
	
	con.style.position = "absolute";
	con.style.left	   = Math.round(left).toString()  +"px";
	con.style.top	   = Math.round(top ).toString()   +"px";
	con.style.width	   = Math.round(wid ).toString() +"px";
	con.style.height   = Math.round(hed ).toString()+"px";
}



function B_GetAvatar(index)
{
	let avatar="";let imgidx=-1;
	if	   (index==0) {avatar="avatar01.png";imgidx=15;}
	else if(index==1) {avatar="avatar02.jpg";imgidx=16;}
	else if(index==2) {avatar="avatar03.jpg";imgidx=17;}
	else if(index==3) {avatar="avatar04.jpg";imgidx=18;}
	else if(index==4) {avatar="avatar05.jpg";imgidx=19;}
	else if(index==5) {avatar="avatar06.jpg";imgidx=20;}
	else if(index==6) {avatar="avatar07.jpg";imgidx=21;}
	else if(index==7) {avatar="avatar08.jpg";imgidx=22;}

	return imgidx;
}

function B_GetAvatarStr(index)
{
	let avatar="";let imgidx=-1;
	if	   (index==0) {avatar="avatar01.png";imgidx=15;}
	else if(index==1) {avatar="avatar02.jpg";imgidx=16;}
	else if(index==2) {avatar="avatar03.jpg";imgidx=17;}
	else if(index==3) {avatar="avatar04.jpg";imgidx=18;}
	else if(index==4) {avatar="avatar05.jpg";imgidx=19;}
	else if(index==5) {avatar="avatar06.jpg";imgidx=20;}
	else if(index==6) {avatar="avatar07.jpg";imgidx=21;}
	else if(index==7) {avatar="avatar08.jpg";imgidx=22;}

	return avatar;
}

//-------------------------------------------------------------------------------------------------
//webpage project start here-----------------------------------------------------------------------
//if(!userid) --> falsy condition

//false
//0
//""        // empty string
//null
//undefined
//NaN

include('../src/login.h'); 
include('../src/log_onoff_control_arrange.h'); 


//DOMContentLoaded--> ready to use js-function
//document.addEventListener("DOMContentLoaded", () => {
//  console.log("DOM ready now");
//});


function getCookie(name) {
  let all = document.cookie;              // "user=aaaa2; theme=dark"
  
  let parts = all.split("; ");            // ["user=aaaa2", "theme=dark"]
  
  for (let i = 0; i < parts.length; i++) {
    if (parts[i].startsWith(name + "=")) {
      let pair = parts[i].split("=");     // ["user", "aaaa2"]
      return pair[1];                     // return value
    }
  }

  return null; // not found
}

function WebLoadImageAll()
{
	theLoginCls = stric( new CLoginClsFunc());

	if	   (theLoginCls.mCurrentHtm=="login"   ){
		G0_ChoiceLoginState();
	}
	else if(theLoginCls.mCurrentHtm=="register"){

	}

}

function GetLoginUserID()
{
	return theLoginCls.mUserID;
}

function GetLoginUserPW()
{
	return theLoginCls.mPW;
}

function CLoginClsFunc()
{
	
	this.mUserID="";
	this.mPW=""	   ;
	this.mMoney=0  ;
	this.mUserName ="";
	this.mNicName  ="";
	this.mCurrentHtm="login";
	
	this.Init = function()
	{
		this.mUserID="";
		this.mPW=""	   ;
		this.mMoney= 0 ;
		this.mUserName ="";
		this.mNicName  ="";
		this.mCurrentHtm="login";
	}

	this.LoginDoneFromSvr = function(userid,pw)
	{
		//let str = Date();               // string
		//let now1 = new Date();
		//let now2 = new Date(str);       // convert to Date
		//let diff = now1 - now2;         // works ?
		//localStorage.setItem(key, value);
		//document.cookie = "sessionId=abc123";//this set only 1 cookie(sessionId)

		//localStorage.setItem("LoginUser",userid);
		//localStorage.setItem("LoginTime",Date());

		this.mUserID=userid;this.mPW=pw;
	}
	this.IsLoginedState = function()
	{
		//using localStorage---------------------------------------------------
		/*
		let result=0;
		let userid	   =localStorage.getItem("LoginUser");
		let loginedtime=localStorage.getItem("LoginTime");
		
		if(userid==null || loginedtime==null) return 0   ;
		if(userid==""   || loginedtime==""  ) return 0   ;
		
		
		let logindate = new Date(loginedtime);if(logindate=="Invalid Date") return 0;
		let now		  = new Date();
		
		let diff=now-logindate;diff=diff/1000;
		
		if(diff > 3600) return 0;
		*/
		//using localStorage---------------------------------------------------


		let sesstion_userid=getCookie("aceholdem_user")
		if(sesstion_userid==null){
			alert("here holdem_user null");
			return 0;
		}
		else{
			alert(sesstion_userid);
		}

		return 1;	 	
	}
};



//webpage project start here-----------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------


