const express = require('express');
const cors = require('cors');
const http = require('http');
const chalk = require('chalk');
const moment = require('moment');
const path = require('path');

class Server {
    db;
    UIPath = path.join(__dirname, '../ui')

    registerRoutes(router) {
        router.post('/join', this.join)
		router.post('/contact', this.contact)
        router.get('/*', this.get)
        return router
    }

    join = (req, res) => {

    }

    contact = (req, res) => {

    }

    get = async (req, res) => {
        console.log(this.UIPath)
        let url = req.url
		let filePath;
		if(url.startsWith("/_")) {
			filePath = path.join(this.UIPath, url);
		} else if(url.includes("75820185")) {
			filePath = path.join(this.UIPath, url.split("75820185")[1]);
		} else {
			filePath = path.join(this.UIPath, "index.html");
		}

		res.sendFile(filePath);
    }

    logRequest(req, res, next) {
        const formattedDate = moment().format('M.D');
        const formattedTime = moment().format('h:mma');
        if(req.url.includes("/api/")) {
            console.log(chalk.blue(`       ${req.method} ${req.url} | ${formattedDate} ${formattedTime}`));
        } else {
            if(req.url === "/")
                console.log(chalk.gray(`       ${req.method} ${req.url} | ${formattedDate} ${formattedTime}`));
        }
        next(); 
    }

    logResponse(req, res, next) {
        const originalSend = res.send;
        res.send = function (body) {
            if(res.statusCode >= 400) {
                console.log(chalk.blue( `<-${chalk.red(res.statusCode)}- ${req.method} ${req.url} | ${chalk.red(body)}`));
            } else {
                console.log(chalk.blue(`<-${res.statusCode}- ${req.method} ${req.url}`));
            }
            originalSend.call(this, body);
        };
        next();
    }

    constructor() {
        const app = express();
        app.use(cors({ origin: '*' }));
        app.use(express.json());
        app.use(express.urlencoded({ extended: true }));

        app.use(this.logRequest);
        app.use(this.logResponse);

        let router = express.Router();
        this.registerRoutes(router)
        app.use('/', router);

        const server = http.createServer(app);
        const PORT = 3004;
        server.listen(PORT, () => {
            console.log("\n")
            console.log(chalk.yellow("*************** Comal YR ***************"))
            console.log(chalk.yellowBright(`Server is running on port ${PORT}: http://localhost`));
            console.log(chalk.yellow("***************************************"))
            console.log("\n")
        });

        process.on('SIGINT', async () => {
            console.log(chalk.red('Closing server...'));
            console.log(chalk.green('Database connection closed.'));
            process.exit(0);
        });

        Object.preventExtensions(this);
    }
}

const server = new Server()