package de.yannicpunktdee.yoshibot.command.commands;

import de.yannicpunktdee.yoshibot.command.YoshiCommand;
import de.yannicpunktdee.yoshibot.command.YoshiCommandContext;
import de.yannicpunktdee.yoshibot.utils.GifSequenceWriter;
import de.yannicpunktdee.yoshibot.utils.Resources;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class BonkCommand extends YoshiCommand {

    public BonkCommand(YoshiCommandContext context) {
        super(context);
    }

    @Override
    public boolean execute() {
        if(!super.execute()) return false;

        File outFile = new File(Resources.getEnsuredTempPath() + UUID.randomUUID().toString() + ".gif");

        try {
            BufferedImage inPicture = ImageIO.read(downloadAttachmentToFile(null, null));
            BufferedImage bonk1Picture = ImageIO.read(new File(Resources.getBonkPngPath() + "bonk1.png"));
            BufferedImage bonk2Picture = ImageIO.read(new File(Resources.getBonkPngPath() + "bonk2.png"));
            BufferedImage frame1 = getOutFrame(bonk1Picture, inPicture, 615, 155, 185, 345);
            ImageOutputStream output = new FileImageOutputStream(outFile);
            GifSequenceWriter writer = new GifSequenceWriter(output, frame1.getType(), 100, true);
            writer.writeToSequence(frame1);
            writer.writeToSequence(getOutFrame(bonk2Picture, inPicture, 455, 155, 345, 345));
            writer.close();
            output.close();
        } catch (IOException e) {
            sendErrorMessage("GIF konnte nicht erstellt werden.");
            return false;
        }

        sendFile(outFile, null);

        return true;
    }

    private BufferedImage getOutFrame(BufferedImage bonkDogGraphics, BufferedImage personGraphics, int x, int y, int width, int height){
        BufferedImage outFrame = new BufferedImage(800, 500, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = outFrame.createGraphics();
        g.setColor(Color.black);
        g.drawImage(personGraphics, x, y, width, height, null);
        g.drawImage(bonkDogGraphics, 0, 0, 680, 412, null);
        return outFrame;
    }

}
