package com.ericsson.uecontrol.core.behaviour;

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

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

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

    @Configurable("File address")
    private String url = "http://speedtest.ftp.otenet.gr/files/test1Mb.db";

    private transient long estimatedDataLength = -1;

    @Override
    protected void execute() throws IOException {
        URL url = new URL(getFileUrl());
        log.debug("Downloading file: " + url);

        byte[] data = new byte[BUFFER_SIZE];
        URLConnection connection = UrlUtil.getURLConnection(url);
        InputStream in = new BufferedInputStream(connection.getInputStream());

        long progress = 0;
        long read = 0;

        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();
    }

    protected String getFileUrl() {
        if(!url.startsWith("http://") && !url.startsWith("https://")
                && !url.startsWith("ftp://"))
            url = "http://"+url;
        return url;
    }


    @Override
    public String getName() {
        return "File Download";
    }

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