package tmcsim.common;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * RevisionNumber represents the current Subversion revision. The Ant build
 * script generates this value and saves it in a plain text file in the 'config'
 * folder. (See target '-pre-compile'). The file should be included into the
 * distributed zip file by the build script so it is available at run time to be
 * displayed in help info.
 *
 * @author jdalbey
 */
public final class RevisionNumber
{

    private static Logger logger = Logger.getLogger("tmcsim.common");
    // Read the subversion revision info and return it
    /**
     * Read the version number from the application properties. The file
     * 'application.properties' is generated by build.xml.
     *
     * @return a version string obtained from application.properties file, or
     * "Version: unknown" if an IOerror prevents us from reading the file.
     */
    public static String getAppVersion()
    {
        String propfilename = "/tmcsim/application.properties";
        String propKey = "Application.revision";
        String version = "unknown";
        try
        {
            Properties props = new Properties();
            props.load(RevisionNumber.class.getResourceAsStream(propfilename));
            version = (String) props.get(propKey);
        } catch (IOException ex)
        {
            Logger.getLogger("tmcsim/common").log(Level.SEVERE,
                    "getAppVersion(): IOError reading " + propfilename);
        } catch (NullPointerException npe)
        {
            Logger.getLogger("tmcsim/common").log(Level.SEVERE,
                    "getAppVersion().load:  Missing file: " + propfilename);
        }
        return "revision: " + version;
    }
    
    /**
     * Return the version number as a string. The revision number is generated
     * by the svnversion command.
     *
     * @see http://svnbook.red-bean.com/en/1.7/svn.ref.svnversion.re.html
     * Currently this string it return untouched. Future enhancements might make
     * it pretty.
     * @return the revision number as a string
     */
    public static String getString()
    {
        String revision = "unknown"; // default
        String kConfigFile = "config/svn-version.txt";
//        InputStream in = RevisionNumber.class.getResourceAsStream("config/svn-version.txt");
        try
        {
            Scanner scan = new Scanner(new File(kConfigFile));
            revision = scan.next();
        } catch (Exception e)
        {
            logger.logp(Level.SEVERE,
                    "RevisionNumber", "getString()",
                    "Exception trying to read from file: "
                    + kConfigFile, e);
        }
        return revision;
    }
}
