package com.ericsson.uecontrol.core.behaviour;

import com.ericsson.uecontrol.core.util.Configurator.Configurable;

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

import java.io.*;

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

    @Configurable(order=1, value="Host")
    private String host     = "ftp.otenet.gr";
    @Configurable(order=2, value="File Path")
    private String filePath = "/test1Mb.db";
    @Configurable(order=3, value="Username")
    private String username = "speedtest";
    @Configurable(order=4, value="Password")
    private String password = "speedtest";

    private transient long estimatedDataLength = -1;

    @Override
    protected void executeFtp(FTPClient ftp) throws IOException {
        log.debug("Downloading FTP file: " + getFtpUrl(filePath));
        InputStream inStream = ftp.retrieveFileStream(filePath);
        if (inStream != null) {
            InputStream in = new BufferedInputStream(inStream);

            // Download data
            long progress = 0;
            long read = 0;
            byte[] data = new byte[BUFFER_SIZE];
            while((read = in.read(data)) != -1 && !stopExecution()){
                progress += read;
                super.setProgress((float)progress/estimatedDataLength);
            }

            estimatedDataLength = progress;
            log.debug("Total download size: "+ estimatedDataLength +" bytes");
            in.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 Download";
    }

    @Override
    public String toString() {
        return "Will download " + getFtpUrl(filePath);
    }
}
