package be.iminds.ilabt.jfed.highlevel.util;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * User: twalcari
 * Date: 6/3/2016
 * Time: 15:41
 */
public class ExternalFileUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ExternalFileUtil.class);

    private final SSHClient ssh;
    private String homedir;

    public ExternalFileUtil(SSHClient ssh) {
        this.ssh = ssh;
    }

    public String getFolder(String fullPath) {
        int separatorLocation = fullPath.lastIndexOf('/');

        String folder;
        if (separatorLocation != -1) {
            folder = fullPath.substring(0, separatorLocation);
        } else {
            LOG.warn("Path {} is an invalid file path", fullPath);
            throw new IllegalArgumentException("Path '" + fullPath + "' is not a valid file path");
        }

        if (folder.contains("~")) {
            if (homedir == null)
                retrieveHomedir();

            assert homedir != null;
            folder = folder.replace("~", homedir);
        }

        return folder;
    }

    private String retrieveHomedir() {
        try (Session session = ssh.startSession()) {
            Session.Command command = session.exec("pwd");
            command.join();
            if (command.getExitStatus() == 0) {
                try (BufferedReader buffer = new BufferedReader(new InputStreamReader(command.getInputStream()))) {
                    homedir = buffer.readLine();
                }
                LOG.info("Retrieved  homedir '{}' from {}", homedir, ssh.getRemoteHostname());

            } else {
                LOG.error("Error while executing 'pwd' on {}", ssh.getRemoteHostname());
            }
        } catch (IOException ex) {
            throw new RuntimeException("Could not retrieve the homefolder on the external system", ex);
        }

        return homedir;
    }

    public String getFilename(String fullPath) {
        int separatorLocation = fullPath.lastIndexOf('/');
        return fullPath.substring(separatorLocation + 1);
    }
}
