package ch.zhaw.gartenverwaltung.json;

import ch.zhaw.gartenverwaltung.io.PlantDatabase;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import javafx.scene.image.Image;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

public class PlantImageDeserializer extends JsonDeserializer<Image> {

    @Override
    public Image deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        Image result = null;
        URL imageUrl = PlantDatabase.class.getResource(String.format("images/%s", parser.getText()));
        if (imageUrl != null) {
            try (InputStream is = new FileInputStream(new File(imageUrl.toURI()))) {
                result = new Image(is);
            } catch (IllegalArgumentException | URISyntaxException e) {
                throw new IOException(String.format("Cannot find Image \"%s\"\n", imageUrl.getFile()));
            }
        }
        return result;
    }
}
