/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2023 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.installer.dialogs.downloader;

import org.jboss.installer.core.LoggerUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class DownloadManager {

    @SuppressWarnings("FieldCanBeLocal")
    private Thread downloadThread;
    private boolean stop = false;
    private CountDownLatch latch = new CountDownLatch(0);

    public void start(List<Download> downloads, DownloadHandler progressHandler) {
        final Runnable runnable = () -> {
            try {
                for (Download download : downloads) {
                    if (stop) {
                        return;
                    }
                    try {
                        download(download, progressHandler);
                    } catch (IOException e) {
                        progressHandler.downloadError(download, e);
                        stop = true;
                        LoggerUtils.systemLog.info("Failed to download resource " + download.getUrl(), e);
                        return;
                    }
                }
                progressHandler.downloadsComplete();
            } finally {
                latch.countDown();
            }
        };
        downloadThread = new Thread(runnable);
        latch = new CountDownLatch(1);
        downloadThread.start();

    }

    public void await() throws InterruptedException {
        latch.await();
    }

    private void download(Download download, DownloadHandler progressHandler) throws IOException {
        final URLConnection conn = download.getUrl().openConnection();

        try(InputStream inputStream = conn.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(download.getOutputPath())) {

            int len = conn.getContentLength();

            int BUFFER_SIZE = 4096;
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            long totalBytesRead = 0;
            int percentCompleted;

            while ((bytesRead = inputStream.read(buffer)) != -1 && !stop) {
                outputStream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                percentCompleted = (int) (totalBytesRead * 100.0 / len);

                if (progressHandler != null) {
                    progressHandler.updateProgress(download, percentCompleted);
                }
            }
        }
    }

    public boolean verify(Download download) {
        try {
            download.getUrl().openStream().close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public void cancel() {
        stop = true;
    }
}
