let colors_html = $("#color_samples_fill div.col").clone();
$("#color_samples_stroke").append(colors_html);

let cnv
let W, H, rad;
let t = 0;
let mouse_down = 0;
let first_load = 1;
let map_info = 0;
let bg_color = "#ffffff";
let erase_color = "#fff";
let stroke_color = "#dd2222";
let stroke_weight = 2;
let fill_color = init_fill_color = stroke_color;
let toggle_scale = strokeCheck = 1;
let isActive;
let tool = "";
let points = [];
let endX = endY = 0;
let oldX = oldY = controlX = controlY = 0;
let visibleText = 0;
let font_size = 32;
let map_scale = 1
let radKM

// For preserving aspect ratio on resize canvas
let main_aspect_ratio = 640/944

W = $("#canvas_wrapper").width();
H = $("#inner_container").height();

cnv_wrapper = document.getElementById("canvas_wrapper");

function setup() {
    cnv = createCanvas(W, H, cnv);
    cnv.parent(cnv_wrapper);
    cnv.hide()
    rectMode(CORNERS);
    cnv.style("position: absolute; z-index:100");

    angleMode(DEGREES)

    clear();
    
    noStroke();

    fill(fill_color);
    textAlign(CENTER, BOTTOM)
    textStyle(BOLD)
    textSize(18)
}

function draw() {

    if (mouse_down) {
        clear();
        rad = dist(mouseX, mouseY, points[0][0], points[0][1])  // Distance in pixels
        radScaled = rad * (1/map_scale) * (1/scaleVal);

        radCM = radScaled/cm_to_px  // Distance in cm
        radKM = radCM * cm_to_km

         if (tool == "line") {
                //textSize(18*(map_scale*2.2))
                clear();
                //noFill();
                stroke(stroke_color);
                strokeWeight(stroke_weight);

            endX =
                keyIsDown(CONTROL) &&
                abs(mouseY - points[0][1]) > abs(mouseX - points[0][0])
                ? points[0][0]
                : mouseX;
            endY =
                keyIsDown(CONTROL) &&
                abs(mouseX - points[0][0]) > abs(mouseY - points[0][1])
                ? points[0][1]
                : mouseY;

            
            line(points[0][0], points[0][1], endX, endY);
            
            circle(points[0][0], points[0][1], 3)
            circle(endX, endY, 3)
            
            dx = (endX - points[0][0])/2
            dy = (endY - points[0][1])/2

            angle = atan(dy/dx);

            push()             
                noStroke()

                translate(points[0][0] + dx, points[0][1] + dy)
                rotate(angle)

                fill(stroke_color)
                text(radKM.toFixed(0), 0, -5)
                
                text('χλμ.', 0, 22)

                //textStyle(NORMAL)
                /// text(radScaled.toFixed(2) + ' ' + radCM.toFixed(2) + ' cm ' + radKM.toFixed(2) + ' km', 0, 22)
            pop()
        } 
    }
}

function mousePressed(e = null) {
    if (e != undefined && e.target.id == cnv.id()) {
        mouse_down = 1;
    }

     if(mouseButton === RIGHT ) { //&& e.target.id == 'map_text' || e.target.id == cnv.id() ) {
            
        $('#line').click()
        if( !$('#line').hasClass('selected')) {
            e.preventDefault()
        }
    }

    points[0] = [mouseX, mouseY];
    oldX = mouseX;
    oldY = mouseY;
    loop()
}

function touchStarted(event) {
    mousePressed(event)
}

function mouseReleased() {
    noLoop()
    oldX = mouseX;
    oldY = mouseY;
    mouse_down = 0;
    if(radKM > 0) {
        setTimeout(function(){
            $('#alert').text('Μέτρηση Απόστασης: ' + radKM.toFixed(0) + ' Χιλιόμετρα')
            radKM = 0
        }, 500)
         
    }
}

document.ontouchmove = function(event){  // Fix for safari
    event.preventDefault();
}

keyPressed = () => {

    if (!visibleText) {
        if ((keyIsDown(CONTROL) && keyCode == 90) ) {
            clear();
/*            if (old_used) {
                image(current_cnv, 0, 0);
            } else {
                image(old_cnv, 0, 0);
            }*/
            old_used = !old_used;
        }

        if (keyCode === CONTROL) {
            controlX = mouseX;
            controlY = mouseY;
        }

        if (keyCode == 66) {
            // 66 => B toggle Countries - borders
            $("#toggle_countries").click();
        }


        if (keyCode == 67) {
            // 67 => C toggle Capitals
            $("#toggle_capitals").click();
        }

        if (keyCode == 75) {
            // 75 => Κ toggle the scale checkbox
            $("#toggle_scale").click();
        }

        if (keyCode == 89) {
            // 89 => Y toggle map info (υπομνημα)
            $("#map_info").click();
        }

         if (keyCode == 76) {
            // 76 => L toggle line
            $("#line").click();
            clear();
        }

        if (keyCode == 83) {
            // 83 => S toggle grid button
            $("#toggle_grid").click();
        }


        if (keyCode == 84) {
            // 84 => T toggle text button
            $("#text").click();
        }

        if (keyCode == 88) {
            // 88 => X toggle toggle_climate button
            $("#toggle_climate").click();
        }

         if (keyCode == 82) {
            // 82 => R reset zoom
            $("#reset").click();
        }

    }
};



function resize_canvas() {
    W = $("#canvas_wrapper").width();

    if (KEEP_MAIN_ASPECT) {
        H = $("#inner_container").fullScreen() ? min(W*(9/13.3), screen.height) : (W*main_aspect_ratio) // based on main aspect
    } else {
        H = $("#inner_container").height();
    }

    if (first_load) {
        if (FIX_IMAGE) {
            preload();
        }
        first_load = 0;
    }

    resizeCanvas(W, H, true);

  cnv.style(`width: ${W}px; height: ${H}px`);
}



// -------- Map controls
$('#climate_map, #background-opacity_wrapper').hide()

$("#toggle_climate").change(function () {

    $('#climate_map, #background-opacity_wrapper').toggle()

    if(map_info){
        if($('#toggle_climate').is(":checked")) {
            $('#base_info').hide()
            $('#climate_info').show()
        }else{
            $('#base_info').show()
            $('#climate_info').hide()
        }
    }

    if($("#background_opacity").val() < 0.8){
        $("#background_opacity").val(0.8).change()
    }
})



$("#toggle_grid").change(function () {
    $('#grid').toggle()
})

$("#toggle_scale").change(function () {
    $('#scale').toggle()
})

$("#toggle_countries").change(function () {
    $('#countries, #palette_icon, #hue').toggle()
   
})

$("#palette_icon").click(function(){
    $("#hue").focus()
})

$("#toggle_capitals").change(function () {
    $('#capitals').toggle()
})


$("#strokeColor").on("input change click", function () {
    $("#color_samples_stroke button").removeClass("active");
    stroke_color = $(this).val();
});

$("#color_samples_stroke button").click(function () {
    $("#color_samples_stroke button").removeClass("active");
    $(this).addClass("active");

    stroke_color = $(this).data("color");
});



// -------- Bg Fill controls

$("#map_info").change(function () {
    map_info = $(this).is(":checked");
    
    if(map_info) {
        if($('#toggle_climate').is(":checked")) {
            $('#base_info').hide()
            $('#climate_info').show()
            if($("#background_opacity").val() < 0.8){
                $("#background_opacity").val(0.8).change()
            }
        }else{
            $('#base_info').show()
            $('#climate_info').hide()
        }
    }else{
        $('#base_info, #climate_info').hide()
    }
});


$("#map_info").change();

$(".standard_buttons button").mousedown(function () {
    isActive = $(this).hasClass("selected");
});


$('#zoom').on('mousemove change', function(){
  scaleVal = $(this).val()
  //$('#wrapper').css({ transformOrigin: '50% 50%'})
  $('#map_wrapper').css({transform: 'scale(' + scaleVal + ')'})
  check_reset()
})


$('#hue').on('mousemove change', function(){
  hue = $(this).val()
  //$('#wrapper').css({ transformOrigin: '50% 50%'})
  $('#countries').css({filter: 'hue-rotate(' + hue + 'deg)'})
})

// -------- change Backround opacity (set to 0.3 in style.css)
$("#background_opacity").on("input change", function () {
    $('#main_map, #climate_info').css("opacity", $(this).val());
});

// -------- Graphic Tools controls (circle, square, text, pencil, etc)
$("#line").click(function () {
    isActive = $(this).hasClass("selected");

    clear()
    cnv.hide()
    tool = $(this).attr("id");

    if (isActive) {
        $(this).removeClass("selected").attr("aria-pressed", "false");
    } else {
        $(this).addClass("selected").attr("aria-pressed", "true");
        cnv.show()
    }

    fill_color = init_fill_color;
});


$("#text").click(function(){
    isActive = $(this).hasClass("selected");  
    if (isActive) {
        $(this).removeClass("selected").attr("aria-pressed", "false");
        $('#map_text').hide()
    } else {
        $(this).addClass("selected").attr("aria-pressed", "true");
        $('#map_text').show()  
    }
})


$("#reset").click(function(){
    scaleVal = 1
    $('#zoom').val(scaleVal).change()
    
    $('#map_wrapper').css({top: '0px', left: '0px'})
    check_reset()
})


function init_controls() {
    //$("#line").click().attr("aria-pressed", "true");
    $("#color_samples_stroke .btn-info, #color_samples_fill .btn-warning, #text")
        .click()
        .addClass("active")
        .attr("aria-pressed", "true");

    //$(".standard_buttons button").click()

    $("#zoom, #background_opacity").val(1);

    if (!$("#toggle_scale").is(":checked")) {
        $("#toggle_scale").prop("checked", true);
    }

    $('#base_info, #climate_info, #grid, #countries, #capitals, #palette_icon, #hue').hide()

    if ($("#toggle_grid").is(":checked")) {
        $("#toggle_grid").click();
        $('#grid').hide()
    }

    if ($("#toggle_climate").is(":checked")) {
        $("#toggle_climate").click();
        $('#climate_map, #background-opacity_wrapper').hide()
    }

    if ($("#toggle_countries").is(":checked")) {
        $("#toggle_countries").click();
        $('#countries, #palette_icon, #hue').hide()
    }


    if ($("#toggle_capitals").is(":checked")) {
        $("#toggle_capitals").click();
        $('#capitals').hide()
    }

    if (!$("#strokeCheck").is(":checked")) {
        $("#strokeCheck").prop("checked", true);
    }


    if ($("#map_info").is(":checked")) {
        $("#map_info").click();
    }

    $("#fillColor").val(fill_color);
    $("#strokeColor").val(stroke_color);
    $("#bgColor").val(bg_color);
}

$('#canvas_wrapper').bind("fullscreenchange", function() {
  setTimeout(function(){resize_canvas()}, 200)
});


// ----------------- Map functionality --------------
$('#map_wrapper').draggable()


scaleVal = 1
$('#map_wrapper')[0].onwheel = (e) => {
    
    e.stopPropagation()

    delta = e.wheelDelta
    scaleVal = parseFloat(scaleVal)

    if(delta > 0) { 
        scaleVal+=0.15             
     } else { 
        scaleVal-=0.15
     }
     
     if(scaleVal < $('#zoom').attr('min')){
      scaleVal = $('#zoom').attr('min')
     }

     if(scaleVal > $('#zoom').attr('max')){
      scaleVal = $('#zoom').attr('max')
     }

    //console.log('scroll: ' + e.clientX + ', ' + e.clientY)

     $('#zoom').val(scaleVal)

     $('#map_wrapper').css({transform: 'scale(' + scaleVal + ')'})

     //signX = (mouseL - originX) < 0 ? 1 : -1
     //signY = (mouseT - originY) < 0 ? 1 : -1

     //$('#map_wrapper').css({left: signX*zoomLeft*mX + 'px', top: signY*zoomTop*mY + 'px'})
     check_reset()
}


function mouseWheel(e) {
    $('#map_wrapper')[0].onwheel(e)
}