package org.apache.sshd.fs.spi;

import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.fs.SftpFileSystem;
import org.apache.sshd.fs.SftpFileSystemProvider;

import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.util.Map;

public class SFTPContext implements Closeable {

    private final SshClient sshClient;

    final SftpFileSystemProvider provider;

    final SftpFileSystem fileSystem;

    public SFTPContext(URI uri, Map<String, ?> env) throws IOException {
        this.sshClient = ClientBuilder.builder().build();
        Object object = env.get("workers");
        if (object instanceof Integer) {
            sshClient.setNioWorkers((Integer) object);
        } else if (object instanceof String) {
            sshClient.setNioWorkers(Integer.parseInt((String) object));
        } else {
            // we do not require a vast pool of threads
            sshClient.setNioWorkers(1);
        }
        sshClient.start();
        this.provider = new SftpFileSystemProvider(sshClient);
        this.fileSystem = provider.newFileSystem(uri, env);
    }

    @Override
    public void close() throws IOException {
        sshClient.stop();
        sshClient.close();
        fileSystem.close();
    }
}
