package com.ericsson.uecontrol.core.behaviour;

import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.ThroughputCalculator;
import com.ericsson.uecontrol.core.util.UrlUtil;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.log4j.Logger;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

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

    @Configurable("Host")
    private String host;
    @Configurable("File Path")
    private String filePath;
    @Configurable("Username")
    private String username;
    @Configurable("Password")
    private String password;
    @Configurable("File Size(Bytes)")
    private int size;


    @Override
    protected void executeFtp(FTPClient ftp) throws IOException {
        log.debug("Uploading to FTP file: " + getFtpUrl(filePath));
        OutputStream outStream = ftp.storeFileStream(filePath);
        if (outStream != null) {
            OutputStream out = new BufferedOutputStream(outStream);

            // Upload data
            int total = 0;
            byte[] data = new byte[BUFFER_SIZE];
            while (total < size && !stopExecution()) {
                int writeLength = (total + data.length < size ? data.length : size - total);
                out.write(data, 0, writeLength);

                total += writeLength;
                super.setProgress((float) total / size);
            }

            out.close();
            if(!ftp.completePendingCommand()) {
                throw new IOException("FTP reply: "+ftp.getReplyString());
            }
        } else {
            throw new IOException("FTP reply: "+ftp.getReplyString());
        }
    }



    @Override
    public String getHost() {
        return host;
    }
    @Override
    public String getUsername() {
        return username;
    }
    @Override
    public String getPassword() {
        return password;
    }


    @Override
    public String getName() {
        return "FTP Upload";
    }

    @Override
    public String toString() {
        return "Will upload a "+ ThroughputCalculator.getByteString(size) +" file.";
    }

}
