import {onRequest} from "firebase-functions/v2/https";
import {readFile} from 'fs/promises';
import canvasGif from 'canvas-gif';

const megamindGif = readFile('megamind.gif');

export const megamind = onRequest({ cors: true }, async (request, response) => {
    const ip = request.ip;
    const res = await fetch('http://ip-api.com/json/' + ip);
    const { city, country } = await res.json();

    // Test info (localhost doesn't have ip obv)
    /*
    const ip = '0.0.0.0';
    const city = 'FakeCity';
    const country = 'FakeCountry';
    */
    
    const gif = await canvasGif(await megamindGif, (ctx, width, height, totalFrames, currFrame) => {
        if (currFrame >= 10) {
            ctx.font = 'bold 40px sans-serif';
            ctx.fillStyle = 'white';
            ctx.fillText(ip, 20, height - 60);
            ctx.fillText(`${city}, ${country}`, 20, height - 20);
        }
    }, { fps: 30 });

    response.contentType('gif');
    response.send(gif);
});
