package be.iminds.ilabt.jfed.util;

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

import java.io.File;
import java.io.IOException;

/**
 * User: twalcari
 * Date: 12/11/13
 * Time: 2:32 PM
 */
public class JFedUtils {
    private static final Logger LOG = LoggerFactory.getLogger(JFedUtils.class);

    /**
     * @return Returns the directory in which all data related to jFed-tools should be stored.
     * If this directory doesn't exist, it is created first.
     * <p/>
     * When the filesystem is inaccessible, null is returned
     */
    public static String getUserDataDirectory() {
        String userDataDir;

        if (System.getProperty("os.name").toLowerCase().contains("win"))
            userDataDir = System.getenv("APPDATA") + File.separator + "jFed" + File.separator;
        else
            userDataDir = System.getProperty("user.home") + File.separator + ".jFed" + File.separator;


        try {
            File userDataDirFile = new File(userDataDir);
            if (!userDataDirFile.exists()) {
                LOG.info("User data dir " + userDataDir + " does not exist. Creating it.");
                if (userDataDirFile.mkdir())
                    return userDataDir;
                else {
                    //probably a user without home dir.
                    //this is NOT an error: the caller might recover from this null return
                    LOG.warn("Could not create the user data directory. (" + userDataDir + ").");
                    return null;
                }
            } else if (userDataDirFile.list() != null)  //check if we can read the file system
                return userDataDir;
            else {
                LOG.error("Unable to list the files in the user data directory");
                return null;
            }


        } catch (SecurityException ex) {
            LOG.error("Unable to create User Data Directory", ex);
            return null;
        }
    }

    public static File getUserDataDirectoryFile() {
        String userDataDir = getUserDataDirectory();

        if (userDataDir != null)
            return new File(userDataDir);
        else
            return null;
    }

    /**
     * returns the user data dir under windows, but instead of a full path, the windows envirement variables are used if possible.
     * <p/>
     * obviosuly only makes sense to call this on windows.
     * <p/>
     * On windows, this points to the same dir as getUserDataDirectory()
     */
    public static String getWindowsUserDataDirectoryString() {
        String ignoreButCreate = getUserDataDirectory();

        return "%APPDATA%" + File.separator + "jFed" + File.separator;
    }


    public static File createPropertiesFile(String filename) {
        boolean fileOk;

        String jFedUserDataDir = getUserDataDirectory();
        if (jFedUserDataDir == null)
            return null;

        File userDataDir = new File(jFedUserDataDir);
        File propertiesFile = new File(userDataDir, "experimenter-ssh.properties");
        if (!propertiesFile.exists()) {
            if (!userDataDir.exists()) {
                LOG.debug("Will try to create " + userDataDir.getPath() + " dir");
                //noinspection ResultOfMethodCallIgnored
                userDataDir.mkdirs();

                if (userDataDir.exists() && userDataDir.isDirectory()) {
                    LOG.info("Successfully created " + userDataDir.getPath() + " dir");
                } else {
                    LOG.error("Could not create jFed user data dir at \"" + userDataDir.getPath() + "\".");
                    return null;
                }
            }

            assert userDataDir.exists();
            try {
                //noinspection ResultOfMethodCallIgnored
                propertiesFile.createNewFile();
            } catch (IOException e) {
                LOG.error("Could not create PropertiesConfiguration file: \"" + e.getMessage() + "\".", e);
                return null;
            }
        }
        assert propertiesFile.exists();

        if (!propertiesFile.canRead())
            LOG.error("WARNING: cannot read jFed properties file: \"" + propertiesFile.getPath() + "\".");

        return propertiesFile;
    }

//see alternative: JFedCommonDialogs.requestEraseJFedConfiguration()
//    /**
//     * WARNING: this method will cause data loss
//     */
//    public static boolean clearUserDataDirectory() {
//        return clearFolder(getUserDataDirectoryFile());
//
//    }
//    private static boolean clearFolder(File folder) {
//        //dangerous: does not support symbolic links
//        for (File file : folder.listFiles()) {
//            if (file.isDirectory()) {
//                if (!clearFolder(file))
//                    return false;
//            }
//            if (!file.delete())
//                return false;
//        }
//        return true;
//    }
}
