import express from 'express';
import path from 'path';
import indexRoutes from './routes/indexRoutes.js';
import {config} from './config.js';
import {cookieService} from './services/cookieService.js';
import cookieParser from 'cookie-parser';
import { Server } from "socket.io";
import cors from 'cors';


const app = express();

// view engine setup
app.set("views", path.join(path.resolve(), "views"));
app.set('view engine', 'hbs');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(path.resolve(), 'public')));
app.use(cookieParser());
app.use(cors());
app.use('/', indexRoutes);

const hostname = config.env.hostname;
const port = normalizePort(process.env.PORT || '7777');

let server = app.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
server.keepAliveTimeout = 0;

export const io = new Server(server);

io.on("connection", socket => {
    socket.on('click', (roomId) => {
        cookieService.incrementCookieClicks(roomId);
        socket.broadcast.emit('change', roomId);
    });
});

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}
