const ws = require('ws');
const http = require('http');
const fs = require('fs');
const url = require('url');

var config = require("./config.js");
var utils = require("./utils.js");
var ws_helpers = require("./ws_helpers.js");

try{
	fs.unlinkSync('/tmp/savox.sock');
	fs.unlinkSync('/tmp/gps.sock');
}
catch(error){
	console.log(error);
};

// create websocket server
let server = http.createServer();
let sockserver = new ws.WebSocketServer({ server : server });
server.listen('/tmp/savox.sock', e=>fs.chmodSync('/tmp/savox.sock', 666));

// create gps server
let gpsServer = http.createServer(function(req, res){
  var queryData = url.parse(req.url, true).query;
  console.log(queryData.lat, queryData.longitude);

  if(config.shouldRecordToServer){
    ws_helpers.recordGPS(queryData.lat, queryData.longitude);
  }

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end();
});
gpsServer.listen('/tmp/gps.sock', e=>fs.chmodSync('/tmp/gps.sock', 666));

sockserver.on('connection', (ws, req) => {
  let clientInfo = utils.parseClientInfo(ws, req);
  ws_helpers.onConnection(ws, clientInfo);

  ws.on('close', () => ws_helpers.onClose(clientInfo));
  ws.on('message', (data) => {
    ws_helpers.onMessage(clientInfo, data);
    if(clientInfo.type == "device")
      ws.send(" ");
  });
  ws.onerror = function (e) { console.log('websocket error', e); };
});

console.log("Server is active.");
