/*
connection:
- clientInfo: object,
- kps
- last contact time
- isClosed 
- requestsDataFrom: ["device name 001", ...]
- other dynamic stuff (?)
*/

let lastDeviceName = undefined;

connections = []
requestsOnDevices = [] // ["uploader1": ["client001", ...]], ...
const ws = require('ws');
const fs = require('fs');
var utils = require("./utils.js");
/*
{
  from: "..",
  to: []
}
*/

var config = require("./config.js");
var consolehelper = require("./consolehelper.js");

function findConnection(idstr){
  var con = connections.find((e) => {
    return e.clientInfo.idstr == idstr;
  })
  return con;
}

function getRequestsForDevice(idstr){
  var requests = requestsOnDevices.find((r) => {
    return r.from == idstr;
  });
  return requests === undefined ? [] : requests.to;
}

function getConnections(){
  return connections;
}

module.exports = {
  recordGPS: function(lat, long){
    try{
      if(lastDeviceName == undefined)
        return;
      // let recordingIndex = config.recordingIndex;
      // let dir = `./fake_camera_footage/${recordingIndex}/`;
      let dir = `./fake_camera_footage/${lastDeviceName}/`;
      let time = new Date() / 1000;
      let filename_gps = dir + "gps_" + time.toString() + ".txt";
      let content = lat + " " + long;

      if(!fs.existsSync(dir)){
        fs.mkdirSync(dir);
      }

      fs.writeFile(filename_gps, content, err => {
        if (err) {
          console.error(err);
        }
      });
    } catch (err) {
      console.error(err);
    }
  },

  onConnection: function (ws, clientInfo) {
    var con = findConnection(clientInfo);

    if(con === undefined){
      connections.push({
        clientInfo: clientInfo,
        bandwidth: 0,
        lastContact: Date.now(),
        isClosed: false,
        requestsDataFrom: [], 
        websocket: ws,
      });
    }
    else{
      con.isClosed = false;
      con.websocket = ws;
    }

    consolehelper.onConnection(clientInfo);
  },

  onClose: function (clientInfo) {
    // var con = findConnection(clientInfo.idstr);
    // if(con !== undefined){
    //   con.isClosed = true;
    //   con.ws = undefined;
    // }
    // remove from list

    connections = connections.filter(c => c.clientInfo.idstr != clientInfo.idstr);

    consolehelper.onClose(clientInfo);
  },
  
  onMessage: function (clientInfo, data) {
    if(config.shouldRecordToServer){
      // let recordingIndex = config.recordingIndex;
      // let dir = `./fake_camera_footage/${recordingIndex}/`;

      lastDeviceName = clientInfo.devicename + clientInfo.timeOfConnect;

      let dir = `./fake_camera_footage/${lastDeviceName}/`;
      let time = new Date() / 1000;
      let filename_hd = dir + "hd_" + time.toString() + ".jpg";
      let filename_thermal = dir + "thermal_" + time.toString() + ".jpg";

      let dataFormatted;
      try{
        dataFormatted = utils.readInFormat(data);
        
        if(!fs.existsSync(dir)){
          fs.mkdirSync(dir);
        }

        if(dataFormatted.hd_data != undefined){
          utils.saveToFile(filename_hd, dataFormatted.hd_data);
        }

        if(dataFormatted.therm_data != undefined){
          utils.saveToFile(filename_thermal, dataFormatted.therm_data);
        }

      }
      catch(err){
        console.log("Error while saving file:", err)
      }
    }

    if(clientInfo.allowedToUpload){
      getConnections().forEach((connection) => {
        if(connection.clientInfo.type == "client"){
          connection.websocket.send(data);
        }
      });
    }

    consolehelper.onMessage(clientInfo, data);
  },
  onError: function (error, clientInfo) {
    consolehelper.onError(error, clientInfo);
  },
}
