package it.integry.integrywmsnative.core.utility;

import android.webkit.URLUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;

public class FileDownloader {

    private String urlString;
    private String destFolder;

    private RunnableArgs<Integer> onProgressUpdate;
    private RunnableArgs<String> onDownloadCompleted;


    public void download() throws Exception {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        String destPathFile;

        try {
            File direct = new File(destFolder);
            if (!direct.exists()) {
                direct.mkdirs();
            }

            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            connection.setConnectTimeout(120 * 1000);

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                throw new Exception("Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage());

            input = connection.getInputStream();
            int totalBytesToDownload = connection.getContentLength();
            int downloadedBytes = 0;

            String title = URLUtil.guessFileName(String.valueOf(url), null, null);

            destPathFile = destFolder + title;

            if (new File(destPathFile).exists())
                new File(destPathFile).delete();

            output = new FileOutputStream(destPathFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = input.read(buf)) > 0) {
                output.write(buf, 0, len);

                downloadedBytes += len;
                if (onProgressUpdate != null)
                    onProgressUpdate.run((downloadedBytes * 100) / totalBytesToDownload);
            }

        } catch (Exception e) {
            throw e;

        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            if (connection != null)
                connection.disconnect();
        }

        if (onDownloadCompleted != null) onDownloadCompleted.run(destPathFile);
    }


    public String getUrlString() {
        return urlString;
    }

    public FileDownloader setUrlString(String urlString) {
        this.urlString = urlString;
        return this;
    }

    public String getDestFolder() {
        return destFolder;
    }

    public FileDownloader setDestFolder(String destFolder) {
        this.destFolder = destFolder;
        return this;
    }

    public FileDownloader setOnProgressUpdate(RunnableArgs<Integer> onProgressUpdate) {
        this.onProgressUpdate = onProgressUpdate;
        return this;
    }

    public FileDownloader setOnDownloadCompleted(RunnableArgs<String> onDownloadCompleted) {
        this.onDownloadCompleted = onDownloadCompleted;
        return this;
    }
}
