import FFmpeg from 'fluent-ffmpeg';
import path from 'path';
import fs from 'fs';
import EventEmitter from 'events';

let inProgress: Array<string> = [];
let funnyListener = new EventEmitter(); 

export default function(ip: string): Promise<string> {
    return new Promise((resolve, reject) => {
        let outPath = path.join(__dirname, '..', 'tmp', ip + '.mp4');

        if (inProgress.indexOf(ip) > -1) {
            console.log('Sending video for ' + ip + ' (awaiting)');
            funnyListener.on(ip, () => {
                resolve(outPath);
            });
        } else {
            if (fs.existsSync(outPath)) {
                console.log('Sending video for ' + ip);
                resolve(outPath);
                return;
            }

            console.log('Generating video for: ' + ip);

            inProgress.push(ip);

            let command = FFmpeg();

            command
                .input(path.join(__dirname, '..', 'assets', 'spongebob.png'))
                .loop(1)
                .input(path.join(__dirname, '..', 'assets', 'coconut.wav'))
                .videoFilter(
                    "drawtext=fontfile=assets/comic.ttf:"
                    + `text='${ip.replace(new RegExp(':', 'g'), '\\:')}':`
                    + "fontcolor=white:"
                    + `fontsize=${ip.length > 15 ? '80' : '150'}:`
                    + "box=1:"
                    + "boxcolor=black@0.3:"
                    + "boxborderw=5:"
                    + "x=(w-text_w)/2:y=(h-text_h)/2:"
                    + "enable='gte(t,8)'")
                .addOption('-t 0:21')
                .addOption('-tune stillimage')
                .addOption('-pix_fmt yuv420p')
                .addOption('-shortest')
                .addOption('-preset veryfast')
                .videoCodec('libx264')
                .audioCodec('aac')
                .output(outPath);

            command.run();

            command.on('end', () => {
                funnyListener.emit(ip);
                funnyListener.removeAllListeners(ip);
                inProgress.splice(inProgress.indexOf(ip), 1);
                resolve(outPath);
            });
        }
    });
}