package biz.redsoft.sample;

import biz.redsoft.util.IncorrectVersionFormat;
import biz.redsoft.util.VersionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Version {
    public static final Logger LOGGER = LoggerFactory.getLogger(Version.class);

    public static final String VERSION_FILE = "version.properties";
    public static final String VERSION_PROP_NAME = "version";

    private static final VersionUtils.Version version = readVersion();

    public static VersionUtils.Version getInstance() {
        return getVersion();
    }

    public static VersionUtils.Version getVersion() {
        return version;
    }

    private static VersionUtils.Version readVersion() {
        final VersionUtils.Version version = new VersionUtils.Version();
        final String packageName = Version.class.getPackage().getName();
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final String versionPath = "META-INF/ncore-product/" + packageName + "/" + VERSION_FILE;
        final InputStream is = classLoader.getResourceAsStream(versionPath);
        if (is != null) {
            loadVersion(version, is);
        } else {
            LOGGER.warn("No version resource at {} Trying to load it from the main package...", versionPath);
            final InputStream oldStream = Version.class.getResourceAsStream(VERSION_FILE);
            if (oldStream != null)
                loadVersion(version, oldStream);
            else
                LOGGER.error("No version resource in classpath");
        }
        return version;
    }

    private static void loadVersion(VersionUtils.Version version, InputStream is) {
        try {
            try {
                final Properties props = new Properties();
                props.load(is);
                final String moduleVersion = props.getProperty(VERSION_PROP_NAME);
                if (moduleVersion != null)
                    version.setVersion(moduleVersion);
                else
                    LOGGER.error("No module.version key in version properties");
            } catch (IncorrectVersionFormat e) {
                LOGGER.error("Error reading version", e);
            } finally {
                is.close();
            }
        }catch (IOException e) {
            LOGGER.error("Error reading version", e);
        }
    }
}