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')
mongoose.connect('mongodb://admin:password@localhost:27017', mongoClientOptions)
    .then(res => console.log('connection Succesful'))
    .catch(err => console.log("errrr"))


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

});

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

parser.on("data", async (data) => {
    try {
        //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')
    }
});


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");

    console.log("client " + ++count);
    // Register a listener on each message of each connection
    client.on("message", (message) => {
        console.log(message.toString());
        console.log("message from");
    });
});

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