package usda.weru.util;

import de.schlichtherle.truezip.file.TFile;
import java.awt.Image;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.swing.JOptionPane;
//import org.apache.log4j.Appender;
//import org.apache.log4j.FileAppender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
//import org.apache.log4j.spi.RootLogger;
import usda.weru.erosion.Erosion;
import usda.weru.resources.Resources;
import usda.weru.weps.Weps;

/*
 *
 * @author joelevin
 */
public class About {

    private static final String VERSION_MAJOR = "version.major";
    private static final String VERSION_MINOR = "version.minor";
    private static final String VERSION_RELEASE = "version.release";
    private static final String BUILD_NUMBER = "build.number";
    private static final String BUILD_RELEASE = "build.release";
    private static final String BUILD_REVISON = "build.revision";
    private static final String BUILD_DATE = "build.date";
    private static final String BUILD_BUILDER = "build.builder";
    private static final String BUILD_ID = "build.id";
    private static final String RELEASE_ID = "release.id";
    private static final String WS_NRCS_FLAG = "release.id.NRCS.flag";
    private static Properties c_properties;

    private static final Logger LOGGER = LogManager.getLogger(About.class);
    static boolean About_weps_db_msg_print = true; /* added to stop printing weps db type messasge multiple times - LEW */
    static boolean About_weps_db_type_msg_print = true; /* added to stop printing weps db type messasge multiple times - LEW */
    private static String user_Home_path; // Added to store {user.home} location if set on command line. -RHK
    private static String Weps_Databases_path; // Added to store databases location if set on command line. -CKM

    private synchronized static Properties getBuildProperties() {
        if (c_properties == null) {
            c_properties = new Properties();
            try {
                c_properties.load(About.class.getResourceAsStream("/build.properties"));
            } catch (IOException ioe) {
                LogManager.getLogger(About.class).warn("Unable to load build.properties.", ioe);
            }
        }
        return c_properties;
    }

    public static String getAbout(usda.weru.util.Application app, Boolean configFiles) {
        StringBuilder buffer = new StringBuilder();
        try {
            buffer.append("Product Version: " + app.getName() + " " + About.getVersion() + "\n");
            buffer.append("Product Release: " + About.getBuildRelease() + "\n");
            buffer.append("Weps data version: " + About.getWepsDataVersion() + "\n");
            buffer.append("Weps Webstart build name: " + getWsBuildName() + "\n");

            if (About.getBuildNumber() > 0) {
                buffer.append("Build: " + About.getBuildNumber() + "\n");
                Date temp = About.getBuildDate();
                String date;
                if(temp == null) date = "";
                else date = About.getBuildDate().toString();
                buffer.append("Build Date: " + temp + "\n");
                buffer.append("Build Revision: " + About.getBuildRevision() + "\n");
                buffer.append("Build Builder: " + About.getBuildBuilder() + "\n");
                buffer.append("Build ID: " + About.getBuildID() + "\n\n");
            } else {
                buffer.append("Build: dev\n");
                buffer.append("Build Date: \n");
                buffer.append("Build Revision: \n\n");
            }

            buffer.append("Java: " + About.getJava() + "\n");
            buffer.append("Java Home: " + About.getJavaHome() + "\n");
            buffer.append("JVM Arguments: " + About.getJVMArgs() + "\n");
            buffer.append("System: " + About.getSystem() + "\n");
            buffer.append("Machine: " + About.getHostName() + " (" + About.getHostAddress() + ")\n\n");

            buffer.append("InstallWepsData: latest download speed average: " + ConfigData.getDefault().getData("CD-WS-DownloadSpeedActualAverage") + " (bytes/sec)" + " and elapsed time: " +  ConfigData.getDefault().getData("CD-WS-DownloadTimeActual") + " (sec)" + "\n\n");
            
            buffer.append("User: " + About.getUserName() + "\n");
            buffer.append("User Home - ${user.home}: " + Util.getProperty("user.home") + "\n");
            buffer.append("User Documents - ${user.documents}: " + Util.getProperty("user.documents") + "\n\n");

            buffer.append("WEPS Home - ${weps.home}: " + Util.getProperty("weps.home") + "\n");
            buffer.append("WEPS Working Directory: " + getUserWorking() + "\n");
            buffer.append("WEPS Databases relative_path - ${weps_db.rdir}: " + Util.getProperty("weps_db.rdir") + "\n");
            buffer.append("WEPS Databases - ${weps.databases}: " + getWepsDatabases().getAbsolutePath() + "\n");
            buffer.append("WEPS Database Directory - ${weps.database_dir}: " + Util.getProperty("weps.database_dir") + "\n\n");

            if (configFiles) {
                buffer.append("Default (Master) Config: " + nonNullFilePath(About.getConfig()) + "\n");
                buffer.append("User (Local) Config: " + nonNullFilePath(About.getUserConfig()) + "\n\n");
            }
            buffer.append("Log: " + nonNullFilePath(About.getLog()) + "\n");
            if(!usda.weru.erosion.Erosion.isSweep()) {
                buffer.append("Log Config: " + nonNullFilePath(About.getLogConfig()) + "\n\n");
            } else {
                buffer.append("Log Config: " + getUserWorking() + "\\cfg\\log.cfg\n\n");
            }
            
            // project information
            buffer.append("Project Path - ${project.path}: " + Util.getProperty("project.path") + "\n");
            if(!usda.weru.erosion.Erosion.isSweep()) {
                buffer.append("Project Directory: " + Util.getProperty("project.directory") + "\n\n"); /* I think this one is: ${project.directory} - LEW 11/9/2020 */
            } else {
                String projDir = usda.weru.erosion.Erosion.getEroName();
                if(projDir == null || projDir.length() == 0) {
                    buffer.append("Project Directory: No saved project selected.\n\n");
                } else {
                    buffer.append("Project Directory: " + usda.weru.erosion.Erosion.getEroName() + "\n\n");
                }
            }

            if(!usda.weru.erosion.Erosion.isSweep()) {
                buffer.append("Current Project: ${project.directory}: " + Util.parse("${project.directory}" + "\n\n"));
                buffer.append("Default Project (variable name): " +  ConfigData.DefaultProjName + "\n"); 
                buffer.append("Default Project (unparsed): " +  ConfigData.getDefault().getData(ConfigData.DefaultProjName) + "\n");
                buffer.append("Default Project (parsed): " + ConfigData.getDefault().getDataParsed(ConfigData.DefaultProjName) + "\n\n");
                // Run information
                buffer.append("New Prj. Default Runs Location - (variable name): " +  ConfigData.NewProjectDefaultRunsLocation + "\n");
                buffer.append("New Prj. Default Runs Location - (unparsed): " +  ConfigData.getDefault().getData(ConfigData.NewProjectDefaultRunsLocation) + "\n");
                buffer.append("New Prj. Default Runs Location - (parsed): " + ConfigData.getDefault().getDataParsed(ConfigData.NewProjectDefaultRunsLocation) + "\n\n");
                // current runs location
                buffer.append("Current Runs Location  (variable name): " +  ConfigData.DefaultRunsLocation + "\n");
                buffer.append("Current Runs Location: " +  ConfigData.getDefault().getDataParsed(ConfigData.DefaultRunsLocation) + "\n\n");
                
                buffer.append("WEPS System Operations Folder (variable name): " + ConfigData.SystemOpDB + "\n");
                buffer.append("WEPS System Operations Folder (unparsed): " + ConfigData.getDefault().getData(ConfigData.SystemOpDB) + "\n");
                buffer.append("WEPS System Operations Folder (parsed): " + ConfigData.getDefault().getDataParsed(ConfigData.SystemOpDB) + "\n\n");
            
                buffer.append("WEPS System Crop/Residue Folder (variable name): " + ConfigData.SystemCropDB + "\n");
                buffer.append("WEPS System Crop/Residue Folder (unparsed): " + ConfigData.getDefault().getData(ConfigData.SystemCropDB) + "\n");
                buffer.append("WEPS System Crop/Residue Folder (parsed): " + ConfigData.getDefault().getDataParsed(ConfigData.SystemCropDB) + "\n\n");
            
                buffer.append("Cligen Data: " + Util.getProperty("cligen.data") + "\n");
                buffer.append("Cligen Index: " + Util.getProperty("cligen.index") + "\n");
            }
            
            buffer.append("Windgen Data: " + Util.getProperty("windgen.data") + "\n");
            buffer.append("Windgen Index: " + Util.getProperty("windgen.index") + "\n");
            // buffer.append("cligen idx file: " + ConfigData.getDefault().getDataParsed("CD-cligen index") + "\n");
            
        } catch (Exception e) {
            LOGGER.warn("Error creating about dialog.", e);
        }

        return buffer.toString();
    }

    private static String nonNullFilePath(TFile file) {
        return file != null ? file.getAbsolutePath() : "";
    }

    public static String getVersion() {
        return getMajorVersion() + "." + getMinorVersion() + "." + getReleaseVersion();
    }

    public static int getMajorVersion() {
        int major = 0;
        String text = getBuildProperties().getProperty(VERSION_MAJOR, "0");
        text = text != null && text.length() > 0 ? text.trim() : "0";
        try {
            major = Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
            major = -1;
            LogManager.getLogger(About.class).warn("Unable to parse build.version: " + text);
        }
        return major;

    }

    public static int getMinorVersion() {
        int minor = 0;
        String text = getBuildProperties().getProperty(VERSION_MINOR, "0");
        text = text != null && text.length() > 0 ? text.trim() : "0";
        try {
            minor = Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
            minor = -1;
            LogManager.getLogger(About.class).warn("Unable to parse build.version: " + text);
        }
        return minor;
    }

    public static int getReleaseVersion() {
        int minor = 0;
        String text = getBuildProperties().getProperty(VERSION_RELEASE, "0");
        text = text != null && text.length() > 0 ? text.trim() : "0";
        try {
            minor = Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
            minor = -1;
            LogManager.getLogger(About.class).warn("Unable to parse build.version: " + text);
        }
        return minor;
    }

    public static int getBuildNumber() {
        int number = 0;
        String text = getBuildProperties().getProperty(BUILD_NUMBER, "0");
        text = text != null && text.length() > 0 ? text.trim() : "0";
        try {
            number = Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
            number = -1;
            LogManager.getLogger(About.class).warn("Unable to parse build.number: " + text);
        }
        return number;
    }

    public static String getBuildRelease() {
        String text = getBuildProperties().getProperty(BUILD_RELEASE, "development");
        if (text == null || text.trim().length() == 0) {
            text = "development";
        }
        return text.trim();
    }

    public static int getBuildRevision() {
        int number = -1;
        String text = getBuildProperties().getProperty(BUILD_REVISON, "-1");
        text = text != null && text.length() > 0 ? text.trim() : "-1";
        try {
            number = Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
            number = -1;
            LogManager.getLogger(About.class).warn("Unable to parse build.revision: " + text);
        }
        return number;
    }

    public static String getBuildBuilder() {
        String text = getBuildProperties().getProperty(BUILD_BUILDER, "ARS");
        if (text == null || text.trim().length() == 0) {
            text = "ARS";
        }
        return text.trim();
    }

    public static String getBuildID() {
        String text = getBuildProperties().getProperty(BUILD_ID, "");
        if (text == null || text.trim().length() == 0) {
            text = "unk";
        }
        return text.trim();
    }

    public static Date getBuildDate() {
        String text = getBuildProperties().getProperty(BUILD_DATE, null);
        if (text == null || text.trim().length() == 0) {
            return null;
        }

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        try {
            return format.parse(text.trim());
        } catch (ParseException pe) {
            LogManager.getLogger(About.class).warn("Unable to parse build.date: " + text);
            return null;
        }
    }
    
    
    protected static String wsBuildname = "ARS_daily";
    
    public static String getWsBuildName() {
        return wsBuildname;
    }

    public static void setWsBuildName(String name) {
        wsBuildname = name;
    }

    public static String getJava() {
        return System.getProperty("java.version") + " (" + System.getProperty("sun.arch.data.model")
                + " bit) from " + System.getProperty("java.vendor");
    }

    public static String getJavaHome() {
        return System.getProperty("java.home");
    }

    public static String getJVMArgs() {
        RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
        List<String> arguments = runtimeMxBean.getInputArguments();
        StringBuilder sb = new StringBuilder();
        for (String arg : arguments) {
            sb.append(arg + " ");
		/* We have very different "-Xbootclasspath args depending upon whether it is using javaws (webstart) or java to run the interface - why? */
	    LogManager.getLogger(About.class).debug("-Xbootclasspath: " + arg);
        }
        return sb.toString();
    }

    public static float getJavaSpecificationVersion() {
        String specVersion = System.getProperty("java.specification.version");

        return Util.parseVersionStringToFloat(specVersion);
    }

    public static String getSystem() {
        return System.getProperty("os.name") + " " + System.getProperty("os.version")
                + " running on " + System.getProperty("os.arch") + "; " + System.getProperty("file.encoding")
                + "; " + Locale.getDefault().toString();
    }

    public static String getOS() {
        return System.getProperty("os.name");
    }

    public static String getOSVersion() {
        return System.getProperty("os.version");
    }

    public static String getPlatform() {
        return System.getProperty("os.arch");
    }

    public static TFile getConfig() {
        try {
            return ConfigData.getDefault().getMainFile();
        } catch (NullPointerException npe) {
            return null;
        }
    }

    public static String getUserName() {
        return System.getProperty("user.name");
    }

    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "";
        }

    }

    public static String getReleaseId() {
        String text = getBuildProperties().getProperty(RELEASE_ID, "dev");
        if (text == null || text.trim().length() == 0) {
            text = "dev";
        }
        if ( (getBuildProperties().getProperty(WS_NRCS_FLAG, "false")).contentEquals("true") ){
            text += "NRCS";
        }

        return text.trim();
    }

    public static String getHostAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return "0.0.0.0";
        }

    }

    public static TFile getUserConfig() {
        try {
            return ConfigData.getDefault().getUserFile();
        } catch (NullPointerException npe) {
            return null;
        }
    }

    private static TFile c_logConfig;

    public static TFile getLogConfig() {
        return c_logConfig;
    }

    public static void setLogConfig(TFile file) {
        c_logConfig = file;
    }
    
    /**
     * 
     * @return TFile
     * A logfile that was created latest. Could be a poor solution, but it 
     * seems to work.
     */
    public static TFile getLog() {
        // LOGGER.warn("testing in about");
        TFile tfl;
        tfl = new TFile(getLatestFilefromDir(getLogFileDir()));
        return tfl;
// MEH log4j need to re-implement
//        Appender appender = LogManager.getRootLogger().getAppender("file");
//        if (appender instanceof FileAppender) {
//            FileAppender fa = (FileAppender) appender;
//            String log = fa.getManager().getFile();
//            if (log != null) {
//                return new TFile(log);
//            }
//        }
//        return null;
    }
    
    
    private static String getLogFileDir(){
        String path = About.getUserWeps().getAbsolutePath() + File.separator+"log";
        
        return path;
    }
    private static String getLatestFilefromDir(String dirPath){
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }

        File lastModifiedFile = files[0];
        for (int i = 1; i < files.length; i++) {
            
           if (lastModifiedFile.lastModified() < files[i].lastModified() && !(files[i].getName().equals("wepsJunk.log"))) {
               lastModifiedFile = files[i];
           }
        }
        return lastModifiedFile.getAbsolutePath();
    }
    public static void setUserHome(String path) {
        user_Home_path = path;
    }
    
    public static TFile getUserHome() {
        if(user_Home_path != null) {
            try {
                TFile userHome_file = new TFile(user_Home_path);
                if (userHome_file.exists())
                    return userHome_file;
            } catch (Exception e) {
                System.err.println("USER HOME LOCATION SET WITH COMMAND LINE PARAMETERS: " + user_Home_path + " FAILED TO OPEN.");
            }
        }
        
        return new TFile(System.getProperty("user.home"));
    }
    
    public static TFile getWepsHome() {
        String os = System.getProperty("os.name");
        String[] osName = os.split(" ");
        if(osName[0].equalsIgnoreCase("Windows"))
        {
            /**
             * To deal with redirects, Windows should not default to the home
             * directory.  To deal with this, we try to move the .weps folder
             * into AppData.
             * 
             * In order of attempting:
             * 1.  AppData\Roaming
             * 2.  AppData\Local
             * 3.  Retry the home directory
             * 4.  AppData\Local\Temp
             * 
             */
           TFile direct = new TFile(System.getenv("APPDATA"));
           if(!direct.canWrite())
           {
               direct = new TFile(System.getenv("LOCALAPPDATA"));
               if(!direct.canWrite())
               {
                   direct = new TFile(System.getProperty("user.home"));
                   if(!direct.canWrite())
                   {
                       direct = new TFile(System.getenv("TEMP"));
                   }
               }
           }
           return direct;
        }
        return new TFile(System.getProperty("user.home"));
    }

    public static TFile getUserDocuments() {
        //return new TFile(TFileSystemView.getFileSystemView().getDefaultDirectory());
        //System.out.println("User Home: " + System.getProperty("user.home"));
        return new TFile(System.getProperty("user.home") + "/" + "Documents");
    }

    private static TFile c_userWepsRoot = null;

    public static TFile getUserWepsRoot() {
        if (c_userWepsRoot == null) {
            c_userWepsRoot = new TFile(getWepsHome(), ".weps/" + getWsBuildName() + "/");
        }
        return c_userWepsRoot;
    }

    public static void setUserWepsRoot(TFile file) {
        c_userWepsRoot = file;
    }

    public static TFile getUserWeps() {
        return new TFile(getUserWepsRoot(), getReleaseId() + "_" + getVersion());
    }

    public static TFile getUserWorking() {
        return new TFile(System.getProperty("user.dir"));
    }

    public static Image getWeruIconImage() {
        return Resources.getImage("weruface3.gif");
    }
    
    /* Set the databases path for about. */
    public static void setDatabases(String path) {
        Weps_Databases_path = path;
    }
    
    /**
     * getWepsDatabases() is called 100's of times. We only want to print out the 
     * first time it can't find the argument specified directory.
     */
    private static boolean printDataBaseError = true;
    
    /**
     * File location for the databases.  This is typically a shared space on the machine.
     * Search Order:
     * 0. Check for command line parameter specified by '-db', and that it exists.
     * 1. Environment variable : WEPS_DATABASES, we be the way *nix systems setup their databases
     *
     * 2 & 3 only on windows boxes
     * 2. %programdata%\weps\databases\, will be the location on vista/7/+ systems
     * 3. %allusersprofile%\Application Data\weps\databases\, will be the location on legacy systems(XP)
     * @return
     */
    public static TFile getWepsDatabases() {
        // Check first to see if command line argument set database path
        if (Weps_Databases_path != null) {
            try {
                TFile db_file = new TFile(Weps_Databases_path);
                if (db_file.exists()) {
                    return db_file; 
                } else {
                    if (printDataBaseError) {
                        String Error = "\nDATABASES LOCATION SET WITH COMMAND LINE PARAMETER (-db): " + Weps_Databases_path + " FAILED TO OPEN.\n";
                        System.err.println(Error);
                        JOptionPane.showMessageDialog(null, Error, db_file.getAbsolutePath(), JOptionPane.ERROR_MESSAGE);
                        System.exit(0);
                        printDataBaseError = false; // only print once
                    }
                }
            } catch (Exception e) {
                // File doesn't exist, can't read, etc.
                System.err.println("DATABASES LOCATION SET WITH COMMAND LINE PARAMETERS: " + Weps_Databases_path + " FAILED TO OPEN.");
            }
        }
        
        if (Weps.isWebstart) {
            if (About_weps_db_msg_print) {
                About_weps_db_msg_print = false;
                LogManager.getLogger(About.class).info("Using webstart databases");
                System.out.println("About.java: Using webstart databases");
            }
            return new TFile(getUserWepsRoot(), "DataBases/");
        } else {
            String env = System.getenv("WEPS_DATABASES");
            if (env != null && env.trim().length() > 0) {
                TFile LinuxTFile = new TFile(env);
                if (About_weps_db_msg_print) {
                    About_weps_db_msg_print = false;
                    LogManager.getLogger(About.class).info("Using WEPS_DATABASES environment variable for database location (Linux): " + LinuxTFile);
                }
                return new TFile(env);
            } else {
                if (About_weps_db_msg_print) {
                    About_weps_db_msg_print = false;
                    LogManager.getLogger(About.class).info("No WEPS_DATABASES env variable set (Linux)");
                }
            }
        }
        
        //if windows then we attempt to figure out where the databases are (for MSI builds)
        if (Util.isWindows()) {
            //1, MSI SWEEP has its own behavior
            if(Erosion.isSweep() && Weps.isMSIbuild) {
                String sweepDbPath = System.getenv("programdata");
                TFile sweep_database = new TFile(sweepDbPath + "\\USDA\\WEPS\\Databases");
                //System.err.println("MSI SWEEP Build selected.");
                //System.err.println("MSI Database Path: " + sweep_database.getAbsolutePath());
                return sweep_database;
            }
            TFile result = null;
            //2, %programdata%\weps\databases
            String programdataPath = System.getenv("programdata");
            if (programdataPath != null && programdataPath.trim().length() > 0) {
                result = new TFile(programdataPath, "USDA\\WEPS\\Databases");
                if (result.isDirectory()) {
                    if (About_weps_db_type_msg_print ==  true) {
                    	About_weps_db_type_msg_print = false;
       		    	LogManager.getLogger(About.class).info("Using MSI databases (Windows Vista/7/10 etc.): " + result);
                    }
                    return result;
                }
            }

            //3. %allusersprofile%\Application Data\weps\databases\,                
            String allusersprofilePath = System.getenv("allusersprofile");
            if (allusersprofilePath != null && allusersprofilePath.trim().length() > 0) {
                result = new TFile(allusersprofilePath, "Application Data\\USDA\\WEPS\\Databases");
                if (result.isDirectory()) {
                    if (About_weps_db_type_msg_print ==  true) {
                    	About_weps_db_type_msg_print = false;
       		    	LogManager.getLogger(About.class).info("Using MSI databases (Windows XP and earlier): " + result);
                    }
                    return result;
                }
            }
            TFile New1TFile = new TFile(".").getCanOrAbsFile();
            // System.out.println("About.java: TFile(\".\").getCanorAbsFile()" + ": "); // + TFile(".").getCanorAbsFile());
            LogManager.getLogger(About.class).info("Which databases(1): " + New1TFile);
            return new TFile(".").getCanOrAbsFile();

        } else {
            TFile New2TFile = new TFile("").getCanOrAbsFile();
            // System.out.println("About.java: TFile(\"\").getCanorAbsFile()" + ": "); // + TFile("").getCanorAbsFile());
            LogManager.getLogger(About.class).info("Which databases(2): "+ New2TFile);
            return new TFile("").getCanOrAbsFile();
        }
    }
    
    public static void setWsNRCSModeFlag() {
        getBuildProperties().setProperty(WS_NRCS_FLAG, "true");
    }
    
    
    public static String getWepsDataVersion () {
        String dataVersion = "";

        TFile verFile = new TFile ("../dataHandler/dataHandler.csip-weps-data-version.txt");

        if (!Weps.isWebstart) {
        	dataVersion = "No data version number (yet) for non-WebStart builds";
        } 
        else if (verFile.exists()) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(verFile));
                dataVersion = reader.readLine();
            } catch (FileNotFoundException ex) {
                dataVersion = "Error: File not found: " + verFile.getAbsolutePath();
            } catch (IOException ex) {
                dataVersion = "Error: File read error: " + verFile.getAbsolutePath();
            }
        }
        else {
            dataVersion = "Error: File not found: " + verFile.getAbsolutePath();            
        }
        LogManager.getLogger(About.class).info("Which databases?: "+ dataVersion);
        return dataVersion;
    }
    
    
    public static TFile getWepsCacheDir () {
        return new TFile(getUserWepsRoot(), "filesCache");
    }
    
    public static TFile getWepsCacheDirTiles () {
        return new TFile(getUserWepsRoot(), "filesCache/tileCache");
    }
    
    public static TFile getOpDirCat(){
        return new TFile(getWepsCacheDir(),"CRLMOD Operations");
    }
    
    public static TFile getOpDirUncat () {
        return new TFile(getWepsCacheDir(), "CrLmod Operations uncat"); 
    }
    
    public static void writeWepsRunningFile () {
        File runningFile = getWepsRunningFile();
        try(FileWriter writer = new FileWriter(runningFile)) {
            String line;
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
            line = dateFormat.format(new Date());
            writer.write(line + System.lineSeparator());
        } catch (IOException ex) {
        }
    }
    
    public static void clearWepsRunningFile () {
        File runningFile = getWepsRunningFile();
        try {
            Files.deleteIfExists(runningFile.toPath());
        } catch (IOException ex) {
        }
    }
    
    public static boolean checkWepsRunningFileExists () {
        return new File (getUserWorking(), "wepsRunning.txt").exists();
    }
    
    public static File getWepsRunningFile() {
        return new File (getUserWorking(), "wepsRunning.txt");
    }
    
}
