import * as math from "../modules/math.js";

var boundsMax = [
  [-255, 0],
  [0, 255],
];

var coordOverlay = L.control({ position: "bottomleft" });
var rectangle = L.rectangle(boundsMax, {color: "#ff7800", weight: 1});

coordOverlay.onAdd = function (map) {
  this._div = L.DomUtil.create("div", "coordinates-overlay");
  this._div.innerHTML = "Cliquez sur la carte pour voir les coordonnées";
  // Empêcher la propagation des clics sur l'overlay à la carte
  L.DomEvent.disableClickPropagation(this._div);
  return this._div;
};

coordOverlay.update = function (coord, cardinal) {
  this._div.innerHTML = "LandBlockId:" + "<br>" + 
  "0x" + coord.x.toString(16).toUpperCase().padStart(2, '0') 
  + "" + coord.y.toString(16).toUpperCase().padStart(2, '0') 
  + "FFFF"
  + "<br>"
  + cardinal;
};


export function RectLandBlock(ev, map) {
  rectangle.remove();
  // Latitude et longitude initiales du coin supérieur gauche du rectangle
  var latlng = ev.latlng;

  //4352
  var pointATmp = map.project(latlng, 4);

  const blockSize = 16; // Taille d'un bloc
  var testReverse = Math.floor((4080 - pointATmp.y) / blockSize);
  var pointA = L.point(Math.round(pointATmp.x), Math.round(pointATmp.y));
  const blockX = Math.floor(pointA.x / blockSize) * 16;
  const blockY = Math.floor(pointA.y / blockSize) * 16;

  var landX = blockX / 16;

  var pointAn = L.point(blockX, blockY);
  var pointB = L.point(blockX + blockSize, blockY + blockSize);
  console.log(pointAn, pointB);
  var latlngA = map.unproject(pointAn, 4); 
  var latlngB = map.unproject(pointB, 4); 

  // Création du rectangle
  var bounds = L.latLngBounds(latlngA, latlngB);
  rectangle = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map)
  .bindPopup("LandBlock : 0x" + landX.toString(16).toUpperCase().padStart(2, '0') 
  + "" + testReverse.toString(16).toUpperCase().padStart(2, '0') + "FFFF");
}

export function UpdateCoord(ev, map) {
    coordOverlay.update(math.GetLandBlockId(ev, map), math.coordToCardinal(ev.latlng.lat, ev.latlng.lng));
}

export default function InitialisationOverlayCoord(map) {
    coordOverlay.addTo(map);
}
