var ctx = document.getElementById("canvas").getContext("2d");
var cv = document.getElementById("canvas");

const fond = new Image();
fond.src = "../../assets/map/map7_recadr.png";
var mapWidth = fond.width
var mapHeith = fond.height
ctx.canvas.width = mapWidth
ctx.canvas.height = mapHeith
ctx.drawImage(fond, 0, 0, mapWidth, mapHeith);


var mode = "circle"

var data = {
    squares: [],
    circles: []
}

var start = []
var stop = []

var w = []

cv.addEventListener("mousedown", (e)=>{
    const rect = canvas.getBoundingClientRect();
    start = [(e.clientX- rect.left) * cv.width / rect.width, (e.clientY - rect.top) * cv.height / rect.height];
})

cv.addEventListener("mouseup", (e)=>{
    const rect = canvas.getBoundingClientRect();
    stop = [(e.clientX- rect.left) * cv.width / rect.width, (e.clientY - rect.top) * cv.height / rect.height];
    w = [-(start[0]-stop[0]), -(start[1]-stop[1])]
    if(mode=="rect"){
        
        data.squares.push({
            x: start[0],
            y: start[1],
            w: w[0],
            h: w[1]
        })
        ctx.fillStyle = "#FF0000"
        ctx.fillRect(start[0], start[1], w[0], w[1]);
    }else if(mode=='circle'){
        var radius = Math.sqrt(w[0]**2 + w[1]**2);
        data.circles.push({
            x: start[0],
            y:start[1],
            r: radius
        })
        ctx.fillStyle="#FF0000"
        ctx.arc(start[0], start[1], radius, 0, 2*Math.PI, false);
        ctx.fill()

    }
    ctx.closePath()
    
})

function circleMode(){
    mode='circle'
}

function rectMode(){
    mode="rect"
}

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);
  
    element.style.display = 'none';
    document.body.appendChild(element);
  
    element.click();
  
    document.body.removeChild(element);
  }

function generateData(){
    download("objects.json", JSON.stringify(data))
}

function render(){
    ctx.fillStyle = "#FF0000"
    ctx.clearRect(0, 0, cv.width, cv.height);
    ctx.drawImage(fond, 0, 0, mapWidth, mapHeith);
    for (let i = 0; i < data.squares.length; i++) {
        ctx.fillRect(data.squares[i].x, data.squares[i].y, data.squares[i].w, data.squares[i].h);
    }
    for (let i = 0; i < data.circles.length; i++) {
        ctx.beginPath()
        ctx.arc(data.circles[i].x, data.circles[i].y, data.circles[i].r, 0, 2*Math.PI, false);
        ctx.fill()
        ctx.closePath();
    }
}

function cancel(){
    if(mode=="rect"){
        data.squares.pop()
    }else if(mode=='circle'){
        data.circles.pop()
    }
    render();
}