package com.jscape.inet.sftp;

/**
* @author Alex Usun
*/
public class PathTools {

    public static final String FILE_SEPARATOR = "/";
    public static final String PARENT_PATH = "..";
    public static final String CURRENT_PATH = ".";

    public static String resolve(String parent, String path) {
        if (isAbsolute(path)) {
            return path;
        }

        if (!PARENT_PATH.equals(path) && !CURRENT_PATH.equals(path) && path.startsWith(CURRENT_PATH + FILE_SEPARATOR)) {
            path = path.substring(2); //
        }

        return successorOf(parent, path);
    }

    public static String nameOf(String path) {
        int index = path.lastIndexOf(FILE_SEPARATOR);
        return index >= 0 && path.length() > index + 1 ? path.substring(index + 1) : path;
    }

    private static boolean isAbsolute(String path) {
        boolean isUnixDir = path.startsWith("/");
        boolean isWinDir = ((path.length() > 1) && Character.isLetter(path.charAt(0)) && (path.charAt(1) == ':'));
        boolean isUNC = path.startsWith("\\\\");
        boolean isStrange = path.contains(":/"); // weird paths like: Home:/, Work:/ etc. Some of VShell servers like to return such paths
        boolean isParent = path.startsWith(PARENT_PATH);
        boolean isCurrent = path.startsWith(CURRENT_PATH);

        return (isUnixDir || isWinDir || isUNC || isStrange) && !isParent && !isCurrent;
    }

    private static String successorOf(String parent, String relative) {
        if (PARENT_PATH.equals(relative)) {
            int position = parent.endsWith(FILE_SEPARATOR) ? parent.lastIndexOf(FILE_SEPARATOR, parent.length() - FILE_SEPARATOR.length() - 1) : parent.lastIndexOf(FILE_SEPARATOR);
            return position > 0 ? parent.substring(0, position) : FILE_SEPARATOR;
        }

        if (!parent.endsWith(FILE_SEPARATOR)) {
            parent += FILE_SEPARATOR;
        }

        if (relative.startsWith(FILE_SEPARATOR)) {
            relative = relative.substring(FILE_SEPARATOR.length());
        }

        return parent + relative;
    }

    private PathTools() {
    }
}
