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;
    }
    if (!req.query.url2) {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({
            error: 'URL2 is required!'
        }))
        return;
    }
    let url = req.query.url;
    let url2 = req.query.url2;
    if (!url.includes('http') && !url.includes('.')) {
        res.send(JSON.stringify({
            error: 'A valid URL must be provided!'
        }))
        return;
    }

    if (!url2.includes('http') && !url2.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: 'URL2 doesn\'t contain any valid image!'
    }))

    if ((!url2.toLowerCase().includes('.png')) && (!url2.toLowerCase().includes('.gif')) && (!url2.toLowerCase().includes('.jpg')) && (!url2.toLowerCase().includes('.jpeg'))) return res.send(JSON.stringify({
        error: 'URL2 doesn\'t contain any 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 image2 = await superagent.get(req.query.url2);
    let img = await sharp(image.body).resize(201, 201).toBuffer();
    let img2 = await sharp(image2.body).resize(201, 201).toBuffer();

    let first = await sharp(`${path.dirname(require.main.filename)}/images/robinBatman.jpeg`)
        .overlayWith(img2, { top: 457, left: 270 })
        .toBuffer();

    await sharp(first)
        .overlayWith(img, { top: 354, left: 589 })
        .toBuffer((err, data, info) => {
            if (err) {
                res.setHeader('Content-Type', 'application/json');
                res.send(JSON.stringify({
                    error: err
                }));
                return;
            }
            res.setHeader('Content-Type', 'image/png'); res.end(data)
        });

};