package ctbrec.ui.tabs.recorded;

import ctbrec.Config;
import ctbrec.StringUtil;
import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Optional;

import static ctbrec.ui.action.AbstractPortraitAction.FORMAT;

public record PortraitStore(Config config) {

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

    public Optional<Image> loadModelPortrait(String modelUrl) {
        return loadModelPortraitFile(modelUrl).map(bytes -> new Image(new ByteArrayInputStream(bytes)));
    }

    public Optional<byte[]> loadModelPortraitFile(String modelUrl) {
        String portraitId = config.getSettings().modelPortraits.get(modelUrl);
        if (StringUtil.isNotBlank(portraitId)) {
            File configDir = config.getConfigDir();
            File portraitDir = new File(configDir, "portraits");
            File portraitFile = new File(portraitDir, portraitId + '.' + FORMAT);
            try {
                return Optional.of(Files.readAllBytes(portraitFile.toPath()));
            } catch (IOException e) {
                LOG.error("Couldn't load portrait file {}", portraitFile, e);
            }
        }
        return Optional.empty();
    }

    public void writePortrait(String id, byte[] data) throws IOException {
        File configDir = config.getConfigDir();
        File portraitDir = new File(configDir, "portraits");
        File portraitFile = new File(portraitDir, id + '.' + FORMAT);
        Files.createDirectories(portraitDir.toPath());
        Files.write(portraitFile.toPath(), data);
    }
}
