const express = require("express");
const app = express();
const fs = require("fs");
const productionData = require("./config/production.js");

const cert = productionData.server.cert;
const key = productionData.server.key;

const options = {
    cert: fs.readFileSync(cert),
    key: fs.readFileSync(key),
};

const server = require("https").createServer(options, app);
const io = require("socket.io")(server, {
    cors: {
        methods: ["GET", "PATCH", "POST", "PUT"],
        origin: true,
        credentials: true,
        transports: ["websocket", "polling"],
    },
});

const redis = require("redis");
var redisClient = redis.createClient();
var redisClientCopy = redis.createClient();
var redisClientMqtt = redis.createClient();

io.on("connection", (socket) => {
    console.log("Client connected");

    redisClient.on("message", function (channel, message) {
        message = JSON.parse(message);
        socket.emit(message.event, message.data);
    });

    redisClientCopy.on("message", function (channel, message) {
        message = JSON.parse(message);
        console.log(message);
        socket.emit(message.event, message.data);
    });

    redisClientMqtt.on("message", function (channel, message) {
        message = JSON.parse(message);
        socket.emit("mqtt-scooter:" + message.identifier, message);
    });

    redisClient.subscribe("chat-channel");
    redisClientCopy.subscribe("private-notification");
    redisClientMqtt.subscribe("mqtt:scooter");

    socket.on("disconnect", function () {
        console.log("Client disconnected");
    });
});

const host = productionData.server.host;
const port = productionData.server.port;

server.listen(port, host, () => {
    console.log(`Server running at https://${host}:${port}`);
});
