/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ctecinf;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author Cássio Conceição
 * @since 06/11/2018
 * @version 201811
 * @see http://ctecinf.com.br/
 */
public class Download {

    public static final String LIB_PATH = "https://ctecinf.com.br/lib/";

    public static void libFromServer(String... libName) throws IOException {

        JTextArea area = new JTextArea();
        area.setBackground(Color.BLACK);
        area.setForeground(Color.GREEN);
        area.setColumns(40);
        area.setRows(8);
        area.setText("Download Biblioteca...");

        final JDialog dialog = new JDialog();
        dialog.setAlwaysOnTop(true);
        dialog.add(new JScrollPane(area));
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);

        for (String lib : libName) {

            String fileURL = LIB_PATH + lib;

            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                String fileName = "";

                String disposition = httpConn.getHeaderField("Content-Disposition");
                Double contentLength = Double.valueOf(httpConn.getHeaderField("Content-Length"));
                String contentType = httpConn.getHeaderField("Content-Type");

                if (disposition != null) {
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10, disposition.length() - 1);
                    }
                } else {
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
                }

                NumberFormat df = DecimalFormat.getNumberInstance();
                df.setGroupingUsed(true);
                df.setMaximumFractionDigits(0);
                df.setMinimumFractionDigits(0);

                area.setText("Baixando [" + contentType + "]: " + fileName + "\n" + area.getText());
                area.setText("Tamanho: " + df.format(contentLength) + " bytes \n" + area.getText());

                System.out.println("Baixando [" + contentType + "]: " + fileName);
                System.out.println("Tamanho: " + df.format(contentLength) + " bytes");

                try (InputStream inputStream = httpConn.getInputStream()) {

                    File saveFile = new File("lib", fileName);

                    if (!saveFile.getParentFile().exists()) {
                        saveFile.getParentFile().mkdirs();
                    }

                    try (FileOutputStream outputStream = new FileOutputStream(saveFile)) {

                        int bytesRead;
                        byte[] buffer = new byte[4096];

                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }

                    area.setText("Download concluido...\n\n" + area.getText());

                    System.out.println("Download concluido...");
                }

            } else {
                area.setText("Sem arquivo [" + fileURL + "]. Server replied HTTP code: " + responseCode + "\n\n" + area.getText());
                System.err.println("Sem arquivo [" + fileURL + "]. Server replied HTTP code: " + responseCode);
            }

            httpConn.disconnect();
        }

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                    System.err.println(ex);
                }

                dialog.dispose();
            }
        }).start();
    }
}
