package ctbrec.ui.action;

import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.ui.controls.Dialogs;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.image.Image;

public class SetThumbAsPortraitAction extends AbstractPortraitAction {

    private static final Logger LOG = LoggerFactory.getLogger(SetThumbAsPortraitAction.class);

    private Image image;

    public SetThumbAsPortraitAction(Node source, Model model, Image image) {
        this.source = source;
        this.model = model;
        this.image = image;
    }

    public void execute() {
        source.setCursor(Cursor.WAIT);
        try {
            BufferedImage bufferedImage = convertFxImageToAwt(image);
            BufferedImage croppedImage = cropImage(bufferedImage);
            BufferedImage portrait = convertToScaledJpg(croppedImage);
            String portraitId = UUID.nameUUIDFromBytes(model.getUrl().getBytes(StandardCharsets.UTF_8)).toString();
            copyToCacheAsJpg(portraitId, portrait);
            Config.getInstance().getSettings().modelPortraits.put(model.getUrl(), portraitId);
            Config.getInstance().save();
            firePortraitChanged();
        } catch (Exception e) {
            LOG.error("Error while changing portrait image", e);
            Dialogs.showError("Set Portrait", "Couldn't change portrait image: ", e);
        }
        source.setCursor(Cursor.DEFAULT);
    }

    private BufferedImage convertFxImageToAwt(Image img) {
        return SwingFXUtils.fromFXImage(img, null);
    }
}
