import * as http from "http";
import crypto from 'crypto';
import express from 'express';
import bodyParser from 'body-parser';
import type { Express } from 'express';
import { createEvent} from 'ics';

interface WebConfig {
    port?: number;
}

const DATE = process.env['DATE'] || 'November 1st';
const TIME = process.env['TIME'] || '2:30PM-5:30PM';

/**
 * I still hate typescript.
 */
function notStupidParseInt(v: string | undefined): number {
    return v === undefined ? NaN : parseInt(v);
}

class Web {
    private _webserver: http.Server | null = null;
    private app: Express | null = null;
    private port: number;
    // private options: WebConfig;

    constructor(options: WebConfig = {}) {
        // this.options = options;
        this.port = notStupidParseInt(process.env['PORT']) || options['port'] as number || 8080;
    }

    initialize = async () => {
        // const options = this.options;
        const app: Express = this.app = express();

        app.set('trust proxy', 1);
        app.set('view engine', 'ejs');
        app.set('view options', { outputFunctionName: 'echo' });
        app.use('/assets', express.static('assets', { maxAge: '30 days' }));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: true }));
        app.use((_req, res, next) => {
            crypto.randomBytes(32, (err, randomBytes) => {
                if (err) {
                    console.error(err);
                    next(err);
                } else {
                    res.locals['cspNonce'] = randomBytes.toString("hex");
                    next();
                }
            });
        });

        app.get('/healthcheck', (_, res) => {
            res.send('Healthy');
        });

        app.get('/', (_, res) => {
            res.render('index', {
                page: {
                    title: 'Madison End of 10 Install Party',
                    titlesuffix: 'Get help installing Linux',
                    description: `Windows 10 support is ending, but you may not need a brand-new PC! Sector67 in Madison, Wisconsin is hosting a Linux install party to help the community keep their current computers usable and up-to-date. Join us on ${DATE}`
                },
                date: DATE,
                time: TIME
            });
        });

        app.get('/os', (_, res) => {
            res.render('os', {
                page: {
                    title: 'Linux Distro Recommendations',
                    titlesuffix: 'madisonlinux.com',
                    description: 'Choosing a Linux distro can be overwhelming. Here are my personal recommendations for beginners and beyond.'
                }
            });
        });

        app.get('/event.ics', (_, res) => {
            createEvent({
                uid: '1@madisonlinux.com',
                start: [2025, 11, 1, 19, 30],
                duration: { hours: 3, minutes: 0 },
                title: 'Madison Linux Workshop',
                description: 'Keep your current PC up-to-date by installing a free OS!',
                location: '56 Corry St, Madison, WI 53704',
                url: 'https://madisonlinux.com/',
                geo: { lat: 43.0982199, lon: -89.3481373 },
                status: 'CONFIRMED',
                busyStatus: 'TENTATIVE',
                organizer: { name: 'Cory Sanin', email: 'endof10@cory.sanin.dev' },
                method: 'REQUEST'
            }, (err, s) => {
                if(err) {
                    console.error(err);
                    res.status(500).send('something went wrong.');
                    return;
                }
                res.set({
                    'Content-Type': 'text/calendar; charset=utf-8',
                    'Content-Disposition': 'attachment; filename="event.ics"'
                }).send(s);
            });
        });

        this._webserver = this.app.listen(this.port, () => console.log(`madisonlinux is running on port ${this.port}`));
    }

    close = () => {
        if (this._webserver) {
            this._webserver.close();
        }
    }
}

export default Web;
export { Web, notStupidParseInt };
export type { WebConfig };
