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';
import path from 'path';
import { promises as fsp } from 'fs';

interface WebConfig {
    port?: number;
}

interface Install {
    os: 'manjaro' | 'mint' | 'chrome' | 'other',
    form: 'laptop' | 'desktop' | 'aio'
}

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 installs: Install[] = [];
    // 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();
        const installPath = process.env['installstat'] || process.env['INSTALLSTAT'] || path.join(process.cwd(), 'config', 'installs.json');
        try {
            this.installs = JSON.parse(await fsp.readFile(installPath, 'utf-8'));
        }
        catch (ex) {
            console.error(ex);
            this.installs = [];
        }


        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((_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');
        });

        const adminParam = process.env['ADMINPARAM'];
        const adminPass = process.env['ADMINPASS'];

        app.get('/', (req, res) => {
            const adminMode = adminParam && adminPass && adminParam in req.query && req.query[adminParam] === adminPass;
            if (req.query?.['utm_medium']) {
                console.log(`${req.query['utm_medium']} | ${req.headers?.['user-agent']}`);
            }
            else if(!adminMode){
                console.log(req.headers?.['user-agent']);
            }
            res.render('lug', {
                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,
                installs: this.installs,
                time: TIME,
                adminMode
            });
        });

        app.post('/', async (req, res) => {
            const adminMode = adminParam && adminPass && adminParam in req.query && req.query[adminParam] === adminPass;
            if (!adminMode) {
                res.redirect('/');
                return;
            }
            const submit = req.body;
            if (!('os' in submit && 'form' in submit)) {
                res.status(400).send('bad request');
                return;
            }
            this.installs.push(submit);
            console.log(`updating ${installPath}`);
            await fsp.writeFile(installPath, JSON.stringify(this.installs, null, 2));
            res.send('ok');
        });

        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('/firefox', (_, res) => {
            res.redirect('https://gist.github.com/CorySanin/d322dc6ebe534c23ba183920d154e566');
        });

        app.get('/event.ics', (_, res) => {
            createEvent({
                uid: '2@madisonlinux.com',
                sequence: 1,
                startInputType: 'local',
                startOutputType: 'local',
                start: [2026, 1, 15, 19, 0],
                duration: { hours: 1, minutes: 0 },
                title: 'Madison Linux User Group',
                description: 'A place for Linux users of all skill levels to meet and share knowledge, troubleshoot, and show off',
                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',
                recurrenceRule: 'FREQ=MONTHLY;BYDAY=TH;BYSETPOS=3'
            }, (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);
            });
        });

        app.use(function (req, res, _) {
            console.log(`404: ${req.url} requested by ${req.ip} "${req.headers['user-agent']}"`);
            res.redirect('/');
        });

        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 };
