package com.ericsson.uecontrol.core.behaviour;

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

import org.apache.log4j.Logger;

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 Logger log = Logger.getLogger(UeBehaviourFileDownload.class);

    @Configurable("File address")
    private String url;


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

        byte[] data = new byte[100];
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.connect();
        InputStream in = connection.getInputStream();

        long total = in.available();
        long progress = 0;
        long read = 0;

        while((read = in.read(data)) != -1 && !stopExecution()){
            progress += read;
            super.setProgress((float)progress/total);
            super.setHandledIncomingData(read);
        }
    }

    protected String getFileUrl() {
        return url;
    }


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

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