// This helped. A lot.
// https://blog.pyrospect.com/2019/01/3-ways-to-run-commands-externally-for.html
// Websocket code adapted from https://medium.com/@martin.sikora/node-js-websocket-simple-chat-tutorial-2def3a841b61
var WebSocketServer = require('websocket').server;
var http = require('http');
const uuidv1 = require('uuid/v1');
var sql = require('mssql');

////////////////////////////////////////
//////////////// Config ////////////////
////////////////////////////////////////

// All events that you want to record
// List here: https://gist.github.com/jocopa3/5f718f4198f1ea91a37e3a9da468675c#file-mcpe-w10-event-names-L48
// WARNING: PlayerTravelled will generate insane amounts of logs.
var events = ["BlockBroken", "BlockPlaced", "ItemAcquired", "ItemCrafted", "ItemDropped", 
              "MobKilled", "PlayerDied", "PlayerMessage"]

var server = http.createServer(function(request, response) {
  // process HTTP request. Since we're writing just WebSockets
  // server we don't have to implement anything.
});

console.log("Starting...");

server.listen(19090, function() { console.log("Listening on 19090"); });

// create the server
wsServer = new WebSocketServer({
  httpServer: server
});

// WebSocket server
wsServer.on('request', function(request) {
  console.log((new Date()) + ' Connection from origin '
      + request.origin + '.');
  
  var connection = request.accept(null, request.origin);
  
  SubscribeAll(connection)
  
  // This is the most important callback for us, we'll handle
  // all messages from users here.
  connection.on('message', function(message) {
    if (message.type === 'utf8') {
        obj = JSON.parse(message.utf8Data);
        // If the message type is a player message, send to the discord webhook, otherwise log it
        if (obj.body.eventName === "PlayerMessage"){
          console.log("Message: [" + obj.body.properties.Sender + "] " + obj.body.properties.Message);
        } else{
          if (obj.body.properties && obj.body.properties.UserId && obj.body.eventName != "PlayerTravelled"){
          writeLog(obj.body.properties.UserId, message.utf8Data);
        }
      }  
    }
  });

  connection.on('close', function(connection) {
    console.log("Connection lost");
  });
});

function SubscribeAll (connection)
{
  events.forEach(event => {
    var json = "{\"body\":{\"eventName\":\""+ event +"\"},\"header\":{\"requestId\":\"" + uuidv1() + "\",\"messagePurpose\":\"subscribe\",\"version\":1,\"messageType\":\"commandRequest\"}}"
    connection.send(json);
  });  
}
