package cd.casic.plugin.pf4j;

import cd.casic.plugin.PluginDescriptorCache;
import cd.casic.plugin.PluginDescriptorStorage;
import cd.casic.plugin.utils.PluginDescriptorUtils;
import org.pf4j.DevelopmentPluginClasspath;
import org.pf4j.PluginDescriptor;
import org.pf4j.PluginRuntimeException;
import org.pf4j.PropertiesPluginDescriptorFinder;
import org.pf4j.util.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

public class OpsPropertiesPluginDescriptorFinder extends PropertiesPluginDescriptorFinder {
    static final DevelopmentPluginClasspath PLUGIN_CLASSPATH = new DevelopmentPluginClasspath();

    public OpsPropertiesPluginDescriptorFinder(){
        super();
    }

    public OpsPropertiesPluginDescriptorFinder(String propertiesFileName){
        super(propertiesFileName);
    }

    @Override
    protected Path getPropertiesPath(Path pluginPath, String propertiesFileName) {
        if (Files.isDirectory(pluginPath)) {
            for (String location : PLUGIN_CLASSPATH.getClassesDirectories()) {
                Path path = pluginPath.resolve(location).resolve(propertiesFileName);
                Resource propertyResource = new FileSystemResource(path);
                if (propertyResource.exists()) {
                    return path;
                }
            }
            throw new PluginRuntimeException(
                    "Unable to find plugin descriptor file: " + DEFAULT_PROPERTIES_FILE_NAME);
        }

        // it's a zip or jar file
        try {
            return FileUtils.getPath(pluginPath, propertiesFileName);
        } catch (IOException e) {
            throw new PluginRuntimeException(e);
        }
    }

    @Override
    public PluginDescriptor find(Path pluginPath) {
        Properties properties = readProperties(pluginPath);
        PluginDescriptorStorage storage = PluginDescriptorUtils.propertiesToStorage(properties);
        PluginDescriptorCache.put(storage.getPluginId(), storage);
        return PluginDescriptorUtils.storageToDescriptor(storage);
    }

}
