const path = require('path');
const superagent = require('superagent');
const fs = require('fs');
const sharp = require('sharp');

module.exports = async (req, res) => {
    if (!req.query.url) {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({
            error: 'URL is required!'
        }))
        return;
    }
    let url = req.query.url;
    if (!url.includes('http') && !url.includes('.')) {
        res.send(JSON.stringify({
            error: 'A valid URL must be provided!'
        }))
        return;
    }

    if ((!url.toLowerCase().includes('.png')) && (!url.toLowerCase().includes('.gif')) && (!url.toLowerCase().includes('.jpg')) && (!url.toLowerCase().includes('.jpeg'))) return res.send(JSON.stringify({
        error: 'This is not a valid image!'
    }))

    let image = await superagent.get(req.query.url).catch(err => { if (err) return res.send(JSON.stringify({ error: 'Failed receiving the image. Check the URL and make sure the image is valid.' })) });
    let img = await sharp(image.body).metadata();
    let hypercam = await sharp(`${path.dirname(require.main.filename)}/images/hypercam.png`).resize(Math.floor((img.width / 100) * 70), Math.floor((img.height / 100) * 70)).max().toBuffer();

    sharp(image.body)
        .overlayWith(hypercam, { gravity: 'northwest' })
        .toBuffer((err, data, info) => {
            if (err) {
                res.setHeader('Content-Type', 'application/json');
                res.send(`{"error":"Something happened. Try again later!"}`);
                return;
            }
            res.setHeader('Content-Type', 'image/png'); res.end(data)
        });
};