'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/passport_local_mongoose_express4');

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

    io.on('go', () => {
        port.write("g");
    });

    io.on('reset', () => {
        port.write("r");
    });
});

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);
                }
            });
            break;
        default:
            io.emit('data', data.toString());
    }
});

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



