package org.kne.codec.kif;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.util.Locale;

/**
 * KIF格式的ImageIO服务提供者。
 * 这个类负责告诉ImageIO：我能处理.kif文件，并且我能创建对应的ImageReader。
 */
public class KIFImageReaderSpi extends ImageReaderSpi {

    // 格式标识信息
    private static final String VENDOR_NAME = "KIFCodec Project";
    private static final String VERSION = "1.0";
    private static final String[] FORMAT_NAMES = {"kif", "KIF"};
    private static final String[] SUFFIXES = {"kif"};
    private static final String[] MIME_TYPES = {"image/kif"};
    private static final String READER_CLASS_NAME = KIFImageReader.class.getName();

    // 标记是否支持流式读取（不支持，因为需要随机访问）
    private static final boolean SUPPORTS_STANDARD_STREAM_METADATA = false;
    private static final boolean SUPPORTS_STANDARD_IMAGE_METADATA = false;

    // 单例实例，避免重复注册
    private static KIFImageReaderSpi instance;

    public KIFImageReaderSpi() {
        super(
            VENDOR_NAME,           // vendorName
            VERSION,               // version
            FORMAT_NAMES,          // names
            SUFFIXES,              // suffixes
            MIME_TYPES,            // MIMETypes
            READER_CLASS_NAME,     // readerClassName
            new Class<?>[]{ImageInputStream.class}, // inputTypes
            null,                  // writerSpiNames
            SUPPORTS_STANDARD_STREAM_METADATA,
            null,                  // nativeStreamMetadataFormatName
            null,                  // nativeStreamMetadataFormatClassName
            null,                  // extraStreamMetadataFormatNames
            null,                  // extraStreamMetadataFormatClassNames
            SUPPORTS_STANDARD_IMAGE_METADATA,
            null,                  // nativeImageMetadataFormatName
            null,                  // nativeImageMetadataFormatClassName
            null,                  // extraImageMetadataFormatNames
            null                   // extraImageMetadataFormatClassNames
        );
    }

    /**
     * 手动注册此插件到 ImageIO 的全局注册表。
     * 调用后，ImageIO 就能识别 .kif 格式。
     * 
     * <p>使用示例：
     * <pre>
     * // 在应用启动时调用一次
     * KIFImageReaderSpi.register();
     * 
     * // 之后就可以正常使用 ImageIO 了
     * BufferedImage img = ImageIO.read(new File("test.kif"));
     * </pre>
     * 
     * @return true 如果注册成功，false 如果已经注册过
     */
    public static void register() {
        IIORegistry registry = IIORegistry.getDefaultInstance();
        
        // 创建实例并注册
        if (instance == null) {
            instance = new KIFImageReaderSpi();
            registry.registerServiceProvider(instance);
        }
    }

    /**
     * 从 ImageIO 的全局注册表中注销此插件。
     * 
     */
    public static void unregister() {
        IIORegistry registry = IIORegistry.getDefaultInstance();
        
        if (instance != null) {
            registry.deregisterServiceProvider(instance);
           
        }
    }

   

    @Override
    public boolean canDecodeInput(Object source) throws IOException {
        if (!(source instanceof ImageInputStream)) {
            return false;
        }

        ImageInputStream stream = (ImageInputStream) source;
        // 保存当前位置
        long pos = stream.getStreamPosition();
        try {
            // 读取文件头魔数（Magic Number）
            byte[] magic = new byte[3];
            stream.readFully(magic);
            
            // 检查是否为 "KIF" (0x4B 0x49 0x46)
            if (magic[0] == 0x4B && magic[1] == 0x49 && magic[2] == 0x46) {
                return true;
            }
            
            return false;
        } finally {
            // 恢复位置
            stream.seek(pos);
        }
    }

    @Override
    public ImageReader createReaderInstance(Object extension) throws IOException {
        return new KIFImageReader(this);
    }

    @Override
    public String getDescription(Locale locale) {
        return "KIF (KIFCodec Image Format) Image Reader";
    }
}