////////////////////////////////////////////////////////////////////////////////////////////////////
//                                         INITIALISATION                                         //

var button = window.document.getElementById("home-go-button");
var warning_text = window.document.getElementById("warning-text");
var loading = window.document.getElementById("home-loading");

var results_container = window.document.getElementById("results");
var multithreading_bar = window.document.getElementById("multithreading-bar");
var singlethreading_bar = window.document.getElementById("singlethreading-bar");
var gpu_bar = window.document.getElementById("gpu-bar");
var multithreading_text = window.document.getElementById("multithreading-text");
var singlethreading_text = window.document.getElementById("singlethreading-text");
var gpu_text = window.document.getElementById("gpu-text");

var aeb_bar = window.document.getElementById("total-bar");
var aeb_text = window.document.getElementById("total-text");

var specs_aeversion_text = window.document.getElementById("aeversion");
var specs_cpu_text = window.document.getElementById("cpu");
var specs_gpu_text = window.document.getElementById("gpu");
var specs_memory_text = window.document.getElementById("memory");
var specs_threads_text = window.document.getElementById("threads");
var specs_os_text = window.document.getElementById("os");
var specs_aeb_text = window.document.getElementById("aeb");

var pe_logo = window.document.getElementById("pe-logo");
var bm_logo = window.document.getElementById("bm-logo");
var re_logo = window.document.getElementById("re-logo");

/** @type {HTMLInputElement} */
/// @ts-ignore
var results_input = window.document.getElementById("results-input");
var submit_button = window.document.getElementById("results-submit-button");


// Start by getting the window location pathname and cutting off the colon if needed
var pathName = window.location.pathname;
if(pathName.search(/\/(\w):\//) === 0) {    // If pathName starts with something like "/C:/" or "/W:/"
    pathName = pathName.replace(/\/(\w):\//, "/$1/");   // We remove the colon, "/C:/..." becomes "/C/..."
}

// The above code works out the platform independent URI string to the extension's, "index.html," file
// Now we give that to our Host object so it knows where to find the external library
Host.setRoot(pathName);
console.log("Setting extension root with pathname:\n" + pathName);


var SUBMITTED = false;


var results = {};

// We use the ping function before checking for requirements so that AE's thread knows to draw the GUI before running our
//  next function
//Host.ping(Host.check_requirements.bind(Host), init);// Check the requirements (such as the existance of the effect)
Host.ping(()=>{
    Host.checkRequirements(init);
});

function init(results)                          // Initalise the panel
{
    window.document.getElementById("status-checking").style.setProperty("display", "none");
    
    console.log(results);
    var effectExists = (results[0] == "true");
    if(!effectExists)
    {
        window.document.getElementById("status-effect").style.setProperty("display", "inherit");
        return;
    }

    button.setAttribute("enabled", "true");
    button.setAttribute("src", "res/img/titleScreen.gif");
    warning_text.style.removeProperty("display");
    initGui();  // Initialise the GUI interaction
}


// GUI interaction and feedback function initialisation
function initGui()
{
    button.addEventListener("click", function(event)
    {
        var debugMode = false;
        if(event.shiftKey) {debugMode = true;}

        button.setAttribute("clicked", "true");
        button.setAttribute("enabled", "false");
        warning_text.style.setProperty("display", "none");

        setTimeout(function(){
            loading.setAttribute("loading", "true");
            setTimeout(function(){
                Host.main(debugMode, displayResults);
                Host.getSpecs(displaySpecs);
            }, 1000);
        }, 800); 
    });

    pe_logo.onclick = function(){window.cep.util.openURLInDefaultBrowser("https://www.plugineverything.com")}
    bm_logo.onclick = function(){window.cep.util.openURLInDefaultBrowser("http://www.aebenchmark.com/")}
    re_logo.onclick = function(){window.cep.util.openURLInDefaultBrowser("https://thewaenderer.com/")}
    document.getElementById("results-goto-benchmark").onclick = function(){window.cep.util.openURLInDefaultBrowser('http://www.aebenchmark.com/')}   

    submit_button.onclick = function(){submitResults();}

    // Setting responsive design
    results_input.oninput = function() {
        var text = results_input.value;
        if(text.length < 1) {
            submit_button.setAttribute("disabled", "true");
        }
        else if (SUBMITTED == false) {
            submit_button.setAttribute("disabled", "false");
        }
    }
}

// Display the results of the benchmark test
/**
 * @param {[number, number, number] | ["ERROR"]} data 
 */
function displayResults(data)
{
    console.log(data);

    loading.removeAttribute("loading");
    if(data[0] == "ERROR"){
        button.removeAttribute("clicked");
        return;
    }
    results_container.setAttribute("enabled", "true");

    // Getting values
    // var max_time = 200;
    // var multithreading_value = (max_time - Number(data[0])) / 2;
    // var singlethreading_value = (max_time - Number(data[1])) / 2;
    // var gpu_value = (max_time - Number(data[2])) / 2;

    var singlethreading_value = Number(data[0]);
    var multithreading_value = Number(data[1]);
    var gpu_value = Number(data[2]);

    // Getting total AEB score
    var aeb_value = (multithreading_value + singlethreading_value + gpu_value) / 3;

    // Setting the width of the results
    singlethreading_bar.style.setProperty("width", (singlethreading_value * 10).toFixed(2) + "px");
    multithreading_bar.style.setProperty("width", (multithreading_value * 10).toFixed(2) + "px");
    gpu_bar.style.setProperty("width", (gpu_value * 10).toFixed(2) + "px");
    aeb_bar.style.setProperty("width", (aeb_value * 10).toFixed(2) + "px");

    // Setting the textcontent of the results
    singlethreading_text.textContent = String(singlethreading_value);
    multithreading_text.textContent = String(multithreading_value);
    gpu_text.textContent = String(gpu_value);
    aeb_text.textContent = String(aeb_value.toFixed(2));
    specs_aeb_text.textContent = String(aeb_value.toFixed(2));


    // Setting global results properties
    results["Singlethreading_Score"] = String(singlethreading_value);
    results["Multithreading_Score"] = String(multithreading_value);
    results["GPU_Score"] = String(gpu_value);
    results["AE_Benchmark_Score"] = String(aeb_value.toFixed(2));
}


// Display the results of the computer specifications
/**
 * @param {array} data 
 */
function displaySpecs(data)
{
    if(data[0] === "ERROR") {
        button.setAttribute("enabled", "true");
        button.removeAttribute("clicked");
        results_container.removeAttribute("enabled");
        warning_text.style.removeProperty("display");
        loading.removeAttribute("loading");
        return;
    }

    var OSName="Unknown OS";
    if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
    if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";

    // Setting global results properties
    results["AE_Version"] = data[4];
    results["CPU"] = data[0];
    results["GPU"] = data[2];
    results["Memory"] = Math.round(Number(data[3]) / 1024) + " GB";
    results["Threads"] = data[1];
    results["Operating_System"] = OSName;


    specs_cpu_text.textContent = results["CPU"];
    specs_threads_text.textContent = results["Threads"];
    specs_gpu_text.textContent = results["GPU"];
    specs_memory_text.textContent = results["Memory"];
    specs_aeversion_text.textContent = results["AE_Version"];
    specs_os_text.textContent = results["Operating_System"];
}


// Sending data to the server
function submitResults()
{
    // Checking if the User has submitted a name, if not we deny the request
    let name = results_input.value;
    if (name.length < 1) {                      // If the text has no length, is an empty string
        window.__adobe_cep__.evalScript("alert('Please enter a name first');", function(){});
        return;
    }

	// Change the button text while we wait for the request
	stateSubmitting();
    
	// Formulate the options for the request
	var https = require('https');
	var options = {
		hostname: 'aebenchmark.com',
		port: 443,
		path: '/score-upload.php',
		method: 'POST'
	};
	
	// Initialse the request with the above options
	var request = https.request(options, (response) => {
		// Define how we handle data coming back from the server in response to our request
		response.on('data', (body) => {
			// Parse the body of the response from a JSON string
            var data = JSON.parse(body.toString());

			// Test if the request was successful or not
			if (response.statusCode == 200) {
				console.log(`Successful request: ${JSON.stringify(data)}`);
                stateSubmitted();

			} else {
				console.error(`Error ${response.statusCode} with response: ${JSON.stringify(data)}`);
				stateSubmittedError();
			}
		});
	});
	
	// Define how we handle any errors in the request object itself
	request.on('error', (e) => {
		console.error(`Error with request: ${e.message}`);
		stateSubmittedError();
    });

    // Getting the name from the user input field
    results["Name"] = name;
    
    // Creating our payload object
    var payload = {
        'Name': results["Name"],
		'AE_Version': results["AE_Version"],
		'CPU': results["CPU"],
		'GPU': results["GPU"],
		'Memory': results["Memory"],
		'Threads': results["Threads"],
		'Operating_System': results["Operating_System"],
		'AE_Benchmark_Score': results["AE_Benchmark_Score"],
		'Multithreading_Score': results["Multithreading_Score"],
		'Singlethreading_Score': results["Singlethreading_Score"],
		'GPU_Score': results["GPU_Score"]
    };

    // Logging the payload for debugging
    console.log(`Sending payload: `);
    console.log(payload);
	
	// Send our data to the server
	request.write(JSON.stringify(payload));
	
	// Finalise the request
	request.end();
}



function stateSubmitting()
{
    console.log("state - Submitting");

    submit_button.textContent = "PLEASE WAIT";
    submit_button.setAttribute("disabled", "true");
    submit_button.onclick = function(){};

    document.getElementById("results-info-text").textContent = "...";
}


function stateSubmitted()
{
    console.log("state - Submitted");
    SUBMITTED = false;

    submit_button.textContent = "SUBMITTED";

    results_input.setAttribute("disabled", "");
    document.getElementById("results-info-text").textContent = "Click on the button below compare your score to others!";
}


function stateSubmittedError()
{
    console.log("state - Submitted Error");

    submit_button.textContent = "SUBMIT TO AEBENCHMARK.COM";
    submit_button.setAttribute("disabled", "false");
    submit_button.onclick = function(){submitResults();}

    results_input.removeAttribute("disabled");
    document.getElementById("results-info-text").textContent = "Unkown error, please try again.";
}