'use strict';
const express = require('express');
const SerialPort = require("serialport");
const mongoose = require('mongoose');
const Readline = require('@serialport/parser-readline');
const scoreModel = require('./mongo-models/score');

const PORT = 8080;
const HOST = '127.0.0.1';

const app = express();

app.use(express.static(__dirname + "/public"));

const port = new SerialPort('COM3', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '\n' }));// Read the port data

port.on("open", () => {
    console.log('Serial port ouvert');
});

const server = require('http').Server(app)
const io = require('socket.io')(server);

mongoose.connect('mongodb://localhost/arduino-basket');

/**
 * Lors de la connexion d'un client
 */
io.on('connection', (socket) => {
    sendBestScores();

    /**
     * Listener sur le 'go' et envoie à l'arduino
     */
    socket.on('go', () => {
        port.write("g");
    });

    /**
     * Listener sur 'reset' et envoie à l'arduino
     */
    socket.on('reset', () => {
        port.write("r");
    });
});

/**
 * Event sur 'data' qui gère les scores et passe les infos au client
 */
parser.on('data', (data) => {
    let dataString = data.toString()
    console.log(dataString);
    let dataSplit = dataString.split(':');
    let type = dataSplit[1];
    switch (type) {
        case 'score':
            let score = dataSplit[2];
            let scoreMongoose = new scoreModel({
                date: Date.now(),
                score: score
            });
            scoreMongoose.save(function (err, scoreDb) {
                if (err) {
                    console.error(err);
                } else {
                    console.log("New score : " + score);
                    sendBestScores();
                }
            });
            break;
        default:
            io.emit('data', data.toString());
    }
});

/**
 * Envoie les 5 meilleurs scores au client
 */
function sendBestScores() {
    scoreModel
        .find({})
        .sort('-score')
        .limit(5)
        .exec((err, bestScores) => {
            if(err) console.log("Error getting the best score");
            else io.emit('bestScores', bestScores);
        });
}

server.listen(PORT, HOST, () => {
    console.log(`Serveur est lancé sur http://${HOST}:${PORT}`);
});



