package com.ericsson.uecontrol.core.behaviour;

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

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
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 UeBehaviour {
    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 execute() throws IOException {
        URL url = new URL(getFileUrl());
        log.debug("Uploading file: " + url);

        byte[] data = new byte[BUFFER_SIZE];
        URLConnection connection = url.openConnection();
        connection.connect();
        OutputStream out = connection.getOutputStream();

        int total = 0;
        while(total < size && !stopExecution()){
            int writeLength = (total+data.length < size ? data.length : total+data.length-size);
            out.write(data, 0, writeLength);

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

    protected String getFileUrl() {
        String url = "ftp://";
        if(username != null && !username.isEmpty()) {
            url += username;
            if(password !=null && !password.isEmpty())
                url += ":"+password;
            url += "@";
        }
        url += host;
        if(filePath != null && !filePath.isEmpty()){
            if(!filePath.startsWith("/"))
                filePath = "/"+filePath;
            url += filePath;
        }
        return url;
    }


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

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

}
