package org.jboss.installer.auto;

import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.dialogs.downloader.Download;
import org.jboss.installer.dialogs.downloader.DownloadHandler;

import java.io.IOException;

public class CliDownloadProgress implements DownloadHandler {

    private final LanguageUtils langUtils;
    private Download currentItem = null;

    public CliDownloadProgress(LanguageUtils langUtils) {
        this.langUtils = langUtils;
    }

    @Override
    public void updateProgress(Download item, int progress) {
        if (currentItem == null) {
            currentItem = item;
            System.out.printf("%s %s %d%%", langUtils.getString("generic.downloading.label"), item.getUrl(), progress);
        } else if (currentItem.getUrl().toExternalForm().equals(item.getUrl().toExternalForm())) {
            System.out.printf("\r%s %s %d%%", langUtils.getString("generic.downloading.label"), item.getUrl(), progress);
        } else {
            System.out.printf("\r%s %s %d%%%n", langUtils.getString("generic.downloading.label"), currentItem.getUrl(), 100);
            currentItem = item;
            System.out.printf("%s %s %d%%", langUtils.getString("generic.downloading.label"), item.getUrl(), progress);
        }
    }

    @Override
    public void downloadsComplete() {
        // go to new line, ready for further logs
        System.out.println();
    }

    @Override
    public void downloadError(Download download, IOException e) {
        System.out.println("\n\n" + langUtils.getString("generic.download.failure", download.getUrl().toString()));
    }
}
