package org.jackhuang.hellominecraft.launcher.util.download;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
/**
 * 用于在文本框中输入URL并创建对应的DownloadManager类的实例
 */
public class DownloadFiles extends JPanel{

    private static final long serialVersionUID = 2575460962137056640L;
    protected JPanel listPanel;//放置各个下载的面板
    protected GridBagConstraints constraints;//指定使用 GridBagLayout类布置的组件的约束。
    protected String filepath;//所下载的文件保存的路径
    private int taskCount = 0;
    static JFrame frame;


    /**
     *
     * @param Title 窗口名称
     * @param URL 下载地址
     * @param path 保存路径
     */
    public DownloadFiles(String Title, String URL, String path){
        File dir = new File(path);
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + path + "成功！");
        }
        try {
            filepath = dir.getCanonicalPath(); //得到的是C:/test/abc;
        } catch (IOException e) {
            e.printStackTrace();
        }
        filepath = filepath + "/";
        frame = new JFrame(Title);
        //DownloadFiles df = new DownloadFiles("http://image.ip5i.com/1.000.0.zip");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(this);
        frame.setSize(700, 400);
        frame.setVisible(true);

        try {
            //设置外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        setLayout(new BorderLayout());
        listPanel = new JPanel();
        listPanel.setLayout(new GridBagLayout());
        constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.weightx = 1;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.anchor = GridBagConstraints.NORTH;
        JScrollPane jsp = new JScrollPane(listPanel);
        add(jsp, BorderLayout.CENTER);

        add(getAddURLPanel(Title, URL), BorderLayout.SOUTH);
    }
    //地址栏、两按钮
    private JPanel getAddURLPanel(String Title, String Url) {
        JPanel panel = new JPanel();
        new Thread(){
            public void run() {
                if(createDownloader(Url)){
                    ++taskCount;
                    frame.setTitle(Title + " 共有："+taskCount+"个下载任务");
                    revalidate();
                }
            }
        }.start();
        return panel;
    }

    private boolean createDownloader(String url) {
        try {
            URL downloadURL = new URL(url);
            URLConnection urlconnection = downloadURL.openConnection();
            int length = urlconnection.getContentLength();
            if(length < 0){
                throw new Exception("无法确定所下载文件的长度!");
            }
            int index = url.lastIndexOf('/');

            File file=new File(filepath+url.substring(index + 1));
            if(file.exists()){
                JOptionPane.showMessageDialog(this, "该文件已经存在",
                        "无法下载", JOptionPane.ERROR_MESSAGE);
                return false;
            }
            FileOutputStream fos = new FileOutputStream(file);

            DownloadManager dm = new DownloadManager(downloadURL, fos);
            listPanel.add(dm, constraints);
            return true;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "该资源无法下载。",
                    "无法下载！", JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }
}
