var img = new Image();
var imgWidth = 0;
var imgHeight = 0;
var currentImage = 0;
var totalImages = 0 ;

var posX = 0;
var posY = 0;
var radius = 0;
var tempRadiusAverage=[];
var tempSpotAverageLong=[];
var tempSpotAverageLat=[];

var clickCount = 0;
var tempClickX = 0;
var tempClickY = 0;

var spotLatitude = 0;
var spotLongitude = 0;

var step1 = false;
var step2 = false;
var ctx = "";
var LIST = [];
var corrections = true;

/* list to do
1) change pointer on step 2 after click
2) Step 2 draw something on canvas to inform user to go to the next image OR just go to next image
3) Ass tatus Image 1 of ##
*/

//Uploader and canvas creator
document.getElementById("uploader").addEventListener('change', function(e) {

    //console.log(e.target.files[0].name);
    if (e.target.files){

        totalImages = e.target.files.length-1; // set the total number of uploaded images
        // create dataset
        for (var i = 0; i < e.target.files.length; i ++){

            //Handle img date
            let fileName = e.target.files[i].name;
            // let imgDate = fileName.substring(fileName.length-12, fileName.length-4); // date is the last 8, last 4 is ".jpeg" characters of th filename
            let imgDate = fileName.replace('_512', '').replace('_1024', ''); //let moment.js try to recognize date pattern
            imgDate = moment(imgDate, moment.defaultFormat).toDate();
            if (moment(imgDate).isValid()){
                // imgDate = moment(imgDate).toDate();
                imgDate = moment(imgDate).toDate();
            } else {
                imgDate = "";
            }


            LIST.push({
                imageBlob: e.target.files[i],
                imageName : e.target.files[i].name,
                date: imgDate,
                radAvg : 0,
                radSD : 0,
                spotPositionLong : 0,
                spotPositionLong_SD : 0,
                spotPositionLat : 0,
                spotPositionLat_SD : 0
            });

        }

        var img = new Image();
        img.src = URL.createObjectURL(e.target.files[currentImage]);
        // console.log(img.event);

        img.onload = () => {
            // get image prop only after image is loaded
            imgWidth = img.width;
            imgHeight = img.height;
            
            //setup canvas
            var imgToAdd = document.createElement("canvas");
            //imgToAdd.setAttribute("src", URL.createObjectURL(this.files[i]));
            imgToAdd.setAttribute("id", "canvas");
            imgToAdd.setAttribute("filename", e.target.files[currentImage].name);
            imgToAdd.setAttribute("width", imgWidth);
            imgToAdd.setAttribute("height", imgHeight);
            imgToAdd.style.background = "url('"+URL.createObjectURL(e.target.files[currentImage])+"') no-repeat";
            imgToAdd.addEventListener("click", getCoordinates);

            //Add a canvas to DOM
            document.getElementById("imgContainer").appendChild(imgToAdd);
            //Context - to global scope
            ctx = document.getElementById("canvas").getContext("2d");
            $("#uploadButton").hide();
            $("#instructions").hide();
            setTimeout(function() { // wait until canvas is fully loaded
                step1button();
            }, 100);
            
        }
    }
});

function getCoordinates(event){
    posX = event.offsetX - (event.target.clientWidth/2);
    posY = -(event.offsetY - (event.target.clientHeight/2)); // positive up, negative down
    radius = Math.sqrt(posX*posX+posY*posY);
    let clickDifference = Math.abs((posX-tempClickX)+(posY-tempClickY));
    // var fileName = event.target.getAttribute("filename");
    console.log(event.target.getAttribute("filename") + " X:" + posX + " Y: " + posY);
    clickCount++;
    //console.log(clickCount);

    //check for the same place clicks
    if ( clickDifference<1 && step1 ) {
        alert('You have clicked at the same spot');
        if (step1){
            clickCount--;
            tempRadiusAverage.pop();
        }

        if (step2){
            clickCount--;
            tempSpotAverageLat.pop();
            tempSpotAverageLong.pop();
        }
    }

    // Define the radius
    if(step1){
        // capture same place clicks
        tempClickX = posX;
        tempClickY = posY;
        drawCoordinates(event.offsetX, event.offsetY);
        tempRadiusAverage.push(radius);
        if (clickCount==5){
            clickCount = 0;
            //let radAvg = (eval(tempRadiusAverage.join('+'))/tempRadiusAverage.length); //tricky way to get an average
            let radAvg = getAverage(tempRadiusAverage);
            let radSD = getSD(tempRadiusAverage);
            LIST[currentImage].radAvg = radAvg; //update DB
            LIST[currentImage].radSD = radSD; //update DB
            drawCircleWithRaduis(radAvg);
            
            //first draw a circle, then ask 
            setTimeout(function(){
                var step_1_confirm = confirm("Please click OK if image of the Sun fits into the purple circle. Click 'Cancel' to start over.");
                if (step_1_confirm){
                    step1 = false; // finish step 1
                    tempRadiusAverage=[]; // reset rsdius calc
                    $("#initialButtons").show();
                    //$("#step1").prop('disabled', false);
                } else {
                    clickCount=0;
                    step1=false;
                    tempRadiusAverage=[]; // reset rsdius calc
                    clearCanvas();
                    step1button();
                    alert("Please, repeat the procedure");
                }
            }, 0);
        }
    }

    //step 2
    if(step2){
        // capture same place clicks
        // tempClickX = posX;
        // tempClickY = posY;

        drawCoordinates(event.offsetX, event.offsetY);
        let radTemp = LIST[0].radAvg; // radius of the first image
        
        console.log("Linear X: "+posX+" Linear Y: "+posY);
        spotLatitude = Math.asin(posY/radTemp);
        spotLongitude = Math.asin(posX/(radTemp*Math.cos(spotLatitude)));

        console.log("Longitude: "+radians_to_degrees(spotLongitude)+"; Latitude: "+radians_to_degrees(spotLatitude));

        if (radius>radTemp){ //click outside of the radius
            console.log("click over the radius");
            alert("You have clicked outside of the radius. Please repeat.");
            clearCanvas();
            clickCount--;
            tempSpotAverageLat.pop();
            tempSpotAverageLong.pop();
        }


        if (clickCount>0&&clickCount<=2){
            setTimeout(function() {
                alert('Click to the spot again (this message increases accuracy of your measurements)');
                setTimeout(function() {
                    clearCanvas();
                }, 10);
            }, 100);
            $('.btn').prop('disabled', true); // disable nav buttons when click
        }else{
            navButtonToggle(); // enable nav buttons when click
        }

        if (clickCount==3){ // step is completed
            setTimeout(function() {
                LIST[currentImage].spotPositionLat = getAverage(tempSpotAverageLat);
                LIST[currentImage].spotPositionLat_SD = getSD(tempSpotAverageLat);
                LIST[currentImage].spotPositionLong = getAverage(tempSpotAverageLong);
                LIST[currentImage].spotPositionLong_SD = getSD(tempSpotAverageLong);
                alert("Data is recorded");
                $("#initialButtons").hide();
                $("#navigationButtons").show();
                setTimeout(function() {
                    clearCanvas();
                    disableClicks();
                }, 10);
            }, 100);
            
        }
        tempSpotAverageLat.push(radians_to_degrees(spotLatitude));
        tempSpotAverageLong.push(radians_to_degrees(spotLongitude));
        /*//capture errors to do
        if ( Math.abs(tempSpotAverageLong[clickCount-2]-tempSpotAverageLong[clickCount-3])>30 && clickCount > 1){
            console.log("for error" + Math.abs(tempSpotAverageLong[clickCount-2]-tempSpotAverageLong[clickCount-3]));
            alert('You have clicked too far');
        }*/

        //workin with appearance of the buttons depending on the current image number
        
    }
}


//Canvas drawing
function drawCoordinates(x,y){	
    let ctx = document.getElementById("canvas").getContext("2d");
    //var ctx = document.getElementById("canvas").getContext("2d");
    ctx.fillStyle = "#ff2626"; // Red color
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, Math.PI * 2); //par 3 - ponit size
    ctx.fill();
}

function drawCircleWithRaduis(radAvg){
    let ctx = document.getElementById("canvas").getContext("2d");
    console.log("insidecrawcircle");
    //var ctx = document.getElementById("canvas").getContext("2d");
    ctx.strokeStyle = "#cc66ff"; // purple
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.arc(imgWidth/2, imgHeight/2, radAvg, 0, Math.PI * 2);
    ctx.stroke();
}

function clearCanvas(){
    let ctx = document.getElementById("canvas").getContext("2d");
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function clearCanvasDot(x,y){
    let ctx = document.getElementById("canvas").getContext("2d");
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}


//Button functions

function step1button (){
    $("#headerMessage").html("Measuring radius of the Sun");
    $("#initialButtons").hide();
    step1 = true;
    clickCount = 0; // reset clicks
    clearCanvas();
    setTimeout(function(){
        alert("Click 5 times on the edge of the Sun in order to calculate the radius of the Sun");
    }, 0);
}

function step2button (){
    clearCanvas();
    step1 = false;
    step2 = true;
    tempRadiusAverage=[];
    tempSpotAverageLat=[];
    tempSpotAverageLong=[];
    clickCount = 0; // reset clicks
    $("#initialButtons").hide();
    $("#navigationButtons").show();
    //$("#imgDate").val(moment((LIST[currentImage].date)).format("YYYY-MM-DD"));
    updateDateInput();
    $("#headerMessage").html(`Measuring position of the spot ${currentImage+1}`);
    $("#headerSubMessage").html(`Image ${currentImage+1} of ${totalImages+1}: (${LIST[currentImage].imageName})`);
    $("#date").show();
    //$('.btn').prop('disabled', true); // Disable all the buttons
    // $(':button').prop('disabled', false); // Enable all the button
    setTimeout(function(){
        alert("Click 3 times on the Center of the chosen spot.");
    }, 0);
}

function step3_next_btn (){
    // check if the dateis not empty
    if ((LIST[currentImage].date) !== "") {
        currentImage++;
        document.getElementById("canvas").style.background = "url('"+URL.createObjectURL(LIST[currentImage].imageBlob)+"') no-repeat";
        updateDateInput();
        $("#headerMessage").html(`Measuring position of the spot ${currentImage+1}`);
        $("#headerSubMessage").html(`Image ${currentImage+1} of ${totalImages+1}: (${LIST[currentImage].imageName})`);
        enableClicks();
        

        clearCanvas();
        step1 = false;
        step2 = true;
        tempRadiusAverage=[];
        tempSpotAverageLat=[];
        tempSpotAverageLong=[];
        clickCount = 0; // reset clicks
        setTimeout(function(){
            alert("Click 3 times on the Center of the chosen spot.");
        }, 100);
    } else {
        alert ("Please enter the date when the imagae was taken.");
    }
}

function step3_prev_btn (){
    // check if the dateis not empty
    if ((LIST[currentImage].date) !== "") {
        currentImage--;
        document.getElementById("canvas").style.background = "url('"+URL.createObjectURL(LIST[currentImage].imageBlob)+"') no-repeat";
        updateDateInput();
        $("#headerMessage").html(`Measuring position of the spot ${currentImage+1}`);
        $("#headerSubMessage").html(`Image ${currentImage+1} of ${totalImages+1}: (${LIST[currentImage].imageName})`);
        enableClicks();

        clearCanvas();
        step1 = false;
        step2 = true;
        tempSpotAverageLat=[];
        tempSpotAverageLong=[];
        clickCount = 0; // reset clicks
        setTimeout(function(){
            alert("Click 3 times on the Center of the chosen spot.");
        }, 100);
    } else {
        alert ("Please enter the date when the imagae was taken.");
    }
}

//************** */

function finish_clicks(){
    if(corrections){
        //correction for Earth movement
        for (var i = 1; i < LIST.length; i++) {
            LIST[i].spotPositionLong = LIST[i].spotPositionLong + (360/365)*(LIST[i].date.getTime()-LIST[0].date.getTime())/(24*3600000);
            // LIST[i].spotPositionLong = LIST[i].spotPositionLong + i*(360/365);
        }
    }
    $("#imgContainer").hide();
    $("#navigationButtons").hide();
    $("#date").hide();
    $("#headerMessage").html(`Showing results and fit`);
    var data = [];
    var averagelat = [];
    for (var i = 0; i < LIST.length; i++) {
        var tempdata = [];
        tempdata.push(LIST[i].date.getTime() / 1000);//use seconds only, not ms
        tempdata.push(LIST[i].spotPositionLong);
        averagelat.push(LIST[i].spotPositionLat);
        data.push(tempdata);
    }
    //console.log(data);
    //fit and chi squiared
    var myRegression = regression('linear', data, { order: 1, precision: 1 });
    var chi2=0
    var temperror=0
    for (var i = 0; i < data.length; i++) {
        temperror=LIST[i].spotPositionLong_SD;
        if (temperror==0) {
            temperror=0.1;
        }
        chi2+=Math.pow((data[i][1]-(myRegression.equation[0]*data[i][0]+myRegression.equation[1])),2)/Math.pow(temperror,2);
    }
    if ((data.length-2)>2) {
        chi2=chi2/(data.length-2);
        }
    else{chi2="Must use at least 5 images";}
    // Plot the result

    $.plot($('.plot'), [
        {data: myRegression.points, label: 'data fit'},
        {data: data, lines: { show: false }, points: { show: true }}
    ]);
    $(".plot_container").show();
    console.log(data);
    console.log(myRegression);
    $("#headerSubMessage").html(`The period of rotation = ${(360/(myRegression.equation[0]*24*3600)).toFixed(3)} days <br> at latitude ${getAverage(averagelat).toFixed(3)} <br> Reduced &chi;<sup>2</sup> = ${chi2} `);
    $("#to_save_as_PNG_button").attr("disabled", false); //show and enable button to download
}


// Math calc
function getAverage(data) {
    return data.reduce(function (a, b) {
        return Number(a) + Number(b);
    }) / data.length;
};

function getSD(data) {
    let m = getAverage(data);
    return Math.sqrt(data.reduce(function (sq, n) {
            return sq + Math.pow(n - m, 2);
        }, 0) / (data.length - 1));
};

function radians_to_degrees(radians){
    var pi = Math.PI;
    return radians * (180/pi);
}

// Utilities and event listeners

function navButtonToggle (){
    if (currentImage<=0){
        $("#step3_prev_btn").prop('disabled', true);
    } else{
        $("#step3_prev_btn").prop('disabled', false);
    }
    if (currentImage>=totalImages){
        $("#step3_next_btn").prop('disabled', true);
        if (clickCount==3){
            $("#finish_clicks").show();//show the finish_clicks button
            $("#finish_clicks").prop('disabled', false);
            $("#step3_next_btn").hide();
        }
    }else{
        $("#step3_next_btn").prop('disabled', false);
    }
}

function updateDateInput () {
    if ((LIST[currentImage].date) == "") {
        $("#imgDateLabel").html("Enter date of the image");
        $("#imgDateLabel").removeClass().addClass("alert alert-danger");
        $("#imgDate").val("");
        disableClicks();
    } else {
        console.log("is date");
        $("#imgDateLabel").html("Date:");
        $("#imgDateLabel").removeClass().addClass("alert alert-primary");
        $("#imgDate").val(moment((LIST[currentImage].date)).format("YYYY-MM-DDTHH:mm"));
        enableClicks();
    }
}

function disableClicks () {
    document.getElementById("canvas").removeEventListener("click", getCoordinates); //disable clicks
    document.getElementById("canvas").style.cursor = "not-allowed";
}

function enableClicks () {
    document.getElementById("canvas").addEventListener("click", getCoordinates); // enable clicks
    document.getElementById("canvas").style.cursor = "";
}

function savePNG(){
    $("#headerMessage").hide();
    $("#to_save_as_PNG_button").hide();
    let to_save = document.body;
    html2canvas(to_save).then(function(canvas) {
        var link = document.createElement("a");
        document.body.appendChild(link);
        link.download = "plot.png";
        link.href = canvas.toDataURL("image/png");
        link.target = '_blank';
        link.click();
    });
}

function correction (event){
	corrections = event.target.checked;
}

//Event listeners
$(".btn").click(function(){
    navButtonToggle();
});

$("#imgDate").change(function(e){
    // console.log(moment(e.target.value).toDate());
    LIST[currentImage].date = moment(e.target.value).toDate(); //update the date with a date object
    updateDateInput ();
});



