const express = require('express');
const app = express();
const fetch = require("node-fetch");

const port = process.env.PORT || 8080; // Use the port provided by the host or default to 3000
app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

// Define a route to handle incoming requests
app.get('/api', (req, res) => {
    // res.send('conned');
    // users.forEach(element => {
    //     if element["id"] == req.
    // });
    res.send(req.query.body)
    if (users[req.query.uuid] === undefined) {
        users[req.query.uuid] = {}
        users[req.query.uuid]["conned"] = true;
        users[req.query.uuid]["id"] = req.query.uuid;
        users[req.query.uuid]["time"] = new Date().valueOf();
        console.log(users);
    } else {
        users[req.query.uuid]["time"] = new Date().valueOf();
    }
});

app.get('/api/main', (req, res) => {
    // res.send('conned');
    // users.forEach(element => {
    //     if element["id"] == req.
    // });
    res.send(req.query.body)
    if (website_viewers[req.query.uuid] === undefined) {
        website_viewers[req.query.uuid] = {}
        website_viewers[req.query.uuid]["conned"] = true;
        website_viewers[req.query.uuid]["id"] = req.query.uuid;
        website_viewers[req.query.uuid]["time"] = new Date().valueOf();
        console.log(website_viewers);
    } else {
        website_viewers[req.query.uuid]["time"] = new Date().valueOf();
    }
});

let website_viewers = {

}

let users = {

}

setInterval(() => {
    check();
}, 2000);


function check() {
    Object.keys(users).forEach(element => {
        // console.log((users[element]["time"] - new Date().valueOf()));
        if ((new Date().valueOf() - users[element]["time"]) > 4000) {
            console.log(`lost ${element}`);
            delete users[element]
        }
    });
    fetch("https://n0r.su/papi/savehouse/?set=stream_viewers&var=" + Object.keys(users).length)
}