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 PatCommand extends YoshiCommand {
	
	public PatCommand(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 pat1Picture= ImageIO.read(new File(Resources.getPatPngPath() + "pat1.png"));
			BufferedImage pat2Picture= ImageIO.read(new File(Resources.getPatPngPath() + "pat2.png"));
			BufferedImage pat3Picture= ImageIO.read(new File(Resources.getPatPngPath() + "pat3.png"));
			BufferedImage frame1 = getOutFrame(pat1Picture, inPicture, 100, 100, 400, 400);
			ImageOutputStream output = new FileImageOutputStream(outFile);
			GifSequenceWriter writer = new GifSequenceWriter(output, frame1.getType(), 100, true);
			writer.writeToSequence(frame1);
			writer.writeToSequence(getOutFrame(pat2Picture, inPicture, 100, 70, 400, 430));
			writer.writeToSequence(getOutFrame(pat3Picture, inPicture, 100, 50, 400, 450));
			writer.close();
			output.close();
		} catch (IOException e) {
			sendErrorMessage("Gif konnte nicht erstellt werden,");
			e.printStackTrace();
			return false;
		}

		sendFile(outFile, null);

		return true;
	}

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

}
