package leigh.mecha.javafx;

import javafx.scene.image.Image;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.Objects;

/**
 * Implementation of {@link RamImageBinder} which loads its images from the local file system (not the resource
 * loader).
 * <p>
 * MTS-safety: Unsafe.
 *
 * @author Alex Leigh
 */
public class FileImageBinder extends RamImageBinder {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(FileImageBinder.class);
    private final String prefix;
    private final String suffix;

    /**
     * Create a new FileImageBinder, that will build file paths using the given prefix and suffixes. The prefix
     * must include "file:", or another valid method for the {@link Image} class.
     */
    public FileImageBinder(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public Image getImage(String name) {
        Image img = super.getImage(name);
        if (img == null) {
            try {
                String fn = prefix + name + suffix;
                logger.debug("Attempting to load icon. [fn: {}]", fn);
                img = new Image(fn);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Can it actually be null? The contract is vague.
            if (img != null) {
                putImage(name, img);
            }
        }
        return img;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FileImageBinder that = (FileImageBinder) o;
        return Objects.equals(prefix, that.prefix) && Objects.equals(suffix, that.suffix);
    }

    @Override
    public int hashCode() {
        return Objects.hash(prefix, suffix);
    }

    @Override
    public String toString() {
        return "FileImageBinder{" +
                "prefix='" + prefix + '\'' +
                ", suffix='" + suffix + '\'' +
                "} " + super.toString();
    }
}
