package com.ericsson.uecontrol.core.behaviour;

import com.ericsson.uecontrol.core.UeBehaviour;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * This behaviour simulates downloading a file from FTP
 *
 * Created by ezivkoc on 2014-07-15.
 */
public abstract class UeBehaviourFtp extends UeBehaviour {
    private static final Logger log = Logger.getLogger(UeBehaviourFtp.class);

    final protected void execute() throws IOException {
        FTPClient ftp = new FTPClient();
        try {
            // Connect
            ftp.setConnectTimeout(5000);
            ftp.setDataTimeout(3000);
            if (getHost().contains(":")) {
                String tmpHost = getHost().substring(0, getHost().indexOf(':'));
                int tmpPort = Integer.parseInt(getHost().substring(getHost().indexOf(':')));
                log.debug("Connecting to host: "+tmpHost+" port: "+tmpPort);
                ftp.connect(tmpHost, tmpPort);
            } else {
                log.debug("Connecting to host: "+getHost());
                ftp.connect(getHost());
            }
            if (getUsername() != null && !getUsername().isEmpty()) {
                log.debug("Login with user: " + getUsername());
                ftp.login(getUsername(), getPassword());
            }
            log.debug("Setting binary mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            log.debug("Setting passive mode");
            ftp.enterLocalPassiveMode();

            executeFtp(ftp);

            // Disconnect
            ftp.logout();
        } finally {
            if(ftp.isConnected()) {
                ftp.disconnect();
            }
        }
    }

    protected String getFtpUrl(String filePath) {
        String url = "ftp://";
        if(getUsername() != null && !getUsername().isEmpty()) {
            url += getUsername();
            if(getPassword() !=null && !getPassword().isEmpty())
                url += ":" + getPassword();
            url += "@";
        }
        url += getHost();
        if(filePath != null && !filePath.isEmpty()){
            if(!filePath.startsWith("/"))
                filePath = "/"+filePath;
            url += filePath;
        }
        return url;
    }


    abstract protected void executeFtp(FTPClient client) throws IOException;

    abstract String getHost();
    abstract String getUsername();
    abstract String getPassword();
}
