const express = require('express');
var fs = require('fs');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
  cors: {
    origin: "http://localhost:8080",
    methods: ["GET", "POST"]
  }
});
    
//setup server for webpage
app.set('port', (process.env.PORT || 8080));

app.use(express.static('public'));

app.listen(app.get('port'), function(err) {
  if (err) {
    console.log(err);
  } else {
    console.log('Running on port: ' + app.get('port')); }
});

//setup communication from serial to server
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');

const port = new SerialPort('/dev/cu.usbserial-1130', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '\n' }));

//setup communication between server and client
io.on('connection', (socket) => {
  console.log('a user connected');
  // Read the serial port data from microcontroller
  port.on("open", () => {
    console.log('serial port open');
  });
  // Send microntroller data to the client
  parser.on('data', data =>{
    console.log('From Microcontroller: ', data);
    socket.emit("data", data);
  });
  socket.on('getLocationData', (location) => {
    console.log("From Server: Received request for wave info at: "+location);
    var data = JSON.parse(fs.readFileSync('./forecasts/'+location+'.json'));
    //read the wave height of the most recent swell for this location
    var waveHeight = data[0].swell.maxBreakingHeight;
    console.log("From Server: Sending wave height in ft. to client: "+waveHeight+"ft.");
    //send wave height to the client for front-end display
    socket.emit("waveHeight", waveHeight);
    //send wave height to phased array for physical display
    port.write([waveHeight], (err) => {
      if (err) {
        return console.log('Error on write: ', err.message);
      }
      console.log('From Server: Sent wave height to microcontroller');
    });
  });
});

io.listen(3000);
