"use strict";

let availableDevices = [];
let selectedDevice = undefined;

function clearCameraFeeds(){
  hd_canvas.getContext("2d").clearRect(0, 0, hd_canvas.width, hd_canvas.height);
  thermal_canvas.getContext("2d").clearRect(0, 0, thermal_canvas.width, thermal_canvas.height);
}

function cameraMenuButtonCallback(devName){
  // Hide map
  if(!map_container.className.includes("hidden")){
    closeMap();
  }

  let canvases = document.getElementsByClassName("camera-canvas");
  for(let canvas of canvases){
    canvas.setAttribute('name', devName);
  }

  // Close panel on mobile
  if(window.innerWidth < 800){
    toggleSidePanel();
  }

  selectedDevice = devName;
  clearCameraFeeds();
}

function addToCameraMenu(devName){
  let newDeviceElement = document.createElement("li");
  newDeviceElement.textContent = devName;
  newDeviceElement.addEventListener('click', () => {
    cameraMenuButtonCallback(devName);
  });

  try {
    deviceList.appendChild(newDeviceElement);
    availableDevices.push(devName);
  } catch (error) {
    console.error(error);
  }
}

function updateCanvas(canvasElement, imgDataJpeg, w, h){
  if(!canvasElement)
    return;
  let blob = new Blob([imgDataJpeg], {'type': 'image/jpeg'});
  let url = URL.createObjectURL(blob);

  if(canvasElement.width != w) canvasElement.width = w;
  if(canvasElement.height != h) canvasElement.height = h;
  let ctx = canvasElement.getContext("2d");
  let img = new Image();
  img.onload = (event) => {
    URL.revokeObjectURL(event.target.src);
    ctx.drawImage(event.target, 0, 0);
  }
  img.src = url;
}

function handleData(data){
  // add device to list, if not included
  if(!availableDevices.includes(data.devicename)){
    addToCameraMenu(data.devicename);
  }
  
  if(data.therm_data !== undefined && data.devicename === selectedDevice){
    let element = Array.from(document.getElementsByClassName("camera-canvas")).find((e) => e.id == "thermal_canvas" && e.getAttribute("name") === selectedDevice);
    updateCanvas(element, data.therm_data, data.therm_w, data.therm_h);
  }
  if(data.hd_data !== undefined && data.devicename === selectedDevice){
    let element = Array.from(document.getElementsByClassName("camera-canvas")).find((e) => e.id == "hd_canvas" && e.getAttribute("name") === selectedDevice);
    updateCanvas(element, data.hd_data, data.hd_w, data.hd_h);
  }
  
  var gpsObj = [
    {
      coordinates: [data.gps_long, data.gps_lat],
      name: data.devicename,
    },
  ];

  updateMap(gpsObj);
}

function connect(){
  let ws=new WebSocket("wss://savox.protopaja.aalto.fi/api/websockets");
  ws.binaryType = "arraybuffer";
 
  ws.addEventListener("open", (e) => {
    console.log("Connected to server.");
  });
  ws.addEventListener("close", (e) => {
    console.log("Disconnected from server, attempting to connect again in 1 second.");
    try{
      setTimeout(() => connect(), 1000);
      return;
    }
    finally{
    }
  });

  ws.addEventListener("message", (e, req) => {
    let dataFormatted = readAndParseFormat(e.data);
    handleData(dataFormatted);
  });
}

connect();
