package org.apache.seatunnel.datasource.plugin.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.hadoop.net.NetUtils;

import io.netty.util.internal.StringUtil;

import java.io.IOException;
import java.net.ConnectException;

public class FtpClientService {

    public static FTPClient connect(FtpConfiguration conf) throws IOException {
        FTPClient client = null;
        String host = conf.getHost();
        int port =
                !StringUtil.isNullOrEmpty(conf.getPort()) ? Integer.parseInt(conf.getPort()) : 21;
        String user = conf.getUser();
        String password = conf.getPassword();
        client = new FTPClient();
        client.connect(host, port);
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw NetUtils.wrapException(
                    host,
                    port,
                    NetUtils.UNKNOWN_HOST,
                    0,
                    new ConnectException("Server response " + reply));
        } else if (client.login(user, password)) {
            client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
            client.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            throw new IOException(
                    "Login failed on server - "
                            + host
                            + ", port - "
                            + port
                            + " as user '"
                            + user
                            + "'");
        }

        return client;
    }
}
