import { IncomingMessage, ServerResponse } from "node:http";
import { FileHandler, File } from "./FileHandler";
import { DataHandler } from "./DataHandler";
import { Database } from "./LocalDatabase";

export class RequestHandler {
    static dh: DataHandler;
    static fh: FileHandler;

    constructor(db: &Database) {
        RequestHandler.dh = new DataHandler(db);
        RequestHandler.fh = new FileHandler();
    }

    new_request(req: IncomingMessage, res: ServerResponse): void {
        if(RequestHandler.dh.valid_uri(req.url)) {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.end(RequestHandler.dh.get_data_json(req.url));
        }
        else if(RequestHandler.fh.file_allowed(req.url)) {
            if(RequestHandler.fh.file_exists(req.url)) {
                res.statusCode = 200;
                let f: File = RequestHandler.fh.file_get(req.url)
                res.setHeader('Content-Type', f.type);
                res.end(f.content);
            } else {
                res.statusCode = 404;
            }
        } else {
            res.statusCode = 403;
        }
        console.log(req.url, res.statusCode);
        res.end();
    }
}
