const SerialPortLib = require("serialport");
const Readline = require("@serialport/parser-readline");
const http = require("http"),
    WebSocketServer = require("ws").Server,
    port = 8080;
const portArduino = new SerialPortLib("/dev/ttyACM0", {baudRate: 9600});
const parser = portArduino.pipe(new Readline({delimiter: "\n"}));
const mongoose = require('mongoose')
const mongoClientOptions = {useNewUrlParser: true, useUnifiedTopology: true, dbName: 'my-app'};
const ChuteModel = require('./ChuteModel');
const {smsSender,smsError} = require('./SmsSender.js')
const clients = [];
mongoose.connect('mongodb://admin:password@mongodb', mongoClientOptions)
    .then(res => console.log('connection Succesful'))
    .catch(err => console.log(err))


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

});

const from = "LI7WAAAAK"
const to = "33766776336"
const text = 'Test sms'


const server = http.createServer();
// create a WebSocket Server on top of the HTTP server to deal with the WebSocket protocol
const wss = new WebSocketServer({
    server,
});

wss.on("connection", (client) => {
    console.log("Client connected");
    clients.push(client);
    // Register a listener on each message of each connection
    client.on("message", (message) => {
        console.log(message.toString());
        console.log("message from");
    });
});

const broadcast = (data) => {
    clients.forEach(client => {
        client.send(data);
    })
}

parser.on("data", async (data) => {
    try {

        broadcast(JSON.stringify({date:new Date()}))
        //smsSender.message.sendSms(from, to, text, smsError)
        let now = new Date();
        const response = await ChuteModel.findOne({when: now.toISOString().slice(0, 10)});
        if (response) {
            await ChuteModel.updateOne(
                {_id: response.id},
                {$set: {nb_chute : response.nb_chute+1}});
        } else {
            const response = new ChuteModel({
                when: now.toISOString().slice(0, 10),
                nb_chute: 1
            }).save();
        }
    } catch (err) {
        console.log('cannot add to the database')
    }
});

// http sever starts listening on given host and port.
server.listen(port, () => {
    console.log(
        "Listening on " + server.address().address + ":" + server.address().port
    );
});