import express from "express"
import fs from "fs"
import path from "path"
import resizeImg from "../../utilities/imgProcessing"

const image = express.Router();



image.get('/', async (req: express.Request, res: express.Response): Promise<void> => {
    let fileName = req.query.filename as string;
    let width = parseInt(req.query.width as string);
    let height = parseInt(req.query.height as string);
    
    // get correct path
    let inputimgPath: string = path.resolve("images/full", `${fileName}.jpg`);
    
    // check if the inputFile exist
    if (!fs.existsSync(inputimgPath)) {
        res.status(404).send("Image not found");
        return;
    }


    // display image if we have fileName, width, height attributs in the request  
    if (fileName && width && height) {

        //resize image
        let outputImg: string = await resizeImg(width, height, fileName);
        res.sendFile(outputImg);

    } else if (fileName) {
        // display original image if we only have filename parameter in the request
        res.sendFile(inputimgPath);
    } else {
        res.status(404).send("Something went wrong");
        return;
    }
})




export default image;