const express = require('express');
const path = require('path');
const pug = require('pug');

const { people, anonImg, getNextID } = require('./data/members');

const app = express();
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// Serve static files (JS, CSS, images, etc.)
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(express.static(__dirname)); // for style.css and clientscript.js in root

// Precompiled templates at startup
const compiledTemplateFunctions = {};
['./views/index.pug', './views/about.pug', './views/profile.pug'].forEach(name => {
    compiledTemplateFunctions[name] = pug.compileFile(`${name}`);
});

// Render function that selects the right compiled template
function renderPage(res, templatePath, data = {}) {
    try {
        const renderFn = compiledTemplateFunctions[templatePath];
        if (!renderFn) {
            res.status(404).send('Template Not Found');
            return;
        }
        const html = renderFn(data);
        res.status(200).send(html);
    } catch (err) {
        console.error(err);
        res.status(500).send('Internal Server Error');
    }
}

// Route: Home
app.get(['/', '/home'], (req, res) => {
    renderPage(res, './views/index.pug', { people });
});

// Route: About
app.get('/about', (req, res) => {
    renderPage(res, './views/about.pug');
});

// Route: Profile (by query ?id=)
app.get('/profile', (req, res) => {
	for (let i=0; i<people.length; i++) {
		if (people[i].id == req.query.id) {
			let person = people[i];
			renderPage(res, './views/profile.pug', { person, anonImg });
            return;
		}
	}
	// If the person is not found, send back an error
	res.status(404).send('Profile not found');
});

// PUT /newprofile – add a new person
app.put('/newprofile', (req, res) => {
    const newPerson = req.body;
    newPerson.id = getNextID();
    newPerson.messages = [];
    people.push(newPerson);
    res.status(200).send();
});

// POST /message – add a message to a profile
app.post('/message', (req, res) => {
    for (let i=0; i<people.length; i++) {
		if (people[i].id === req.body.id) {
			people[i].messages.push(req.body.message); // add it
			res.status(200).send();
            return;
		}
	}
    res.status(404).send('Person not found');
});

// Catch everything else as 404 Not Found
app.use((req, res) => {
    res.status(404).send('Error 404: Resource not found.');
});

// Start the server
app.listen(PORT);
console.log(`Express server running at http://localhost:${PORT}`);