package cn.qmai.study.java.demo1;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 同时下载8首歌
 *
 * @author 宋欢
 */
public class DownloadMp3 {
    /**
     * 默认的连接超时，单位：毫秒
     */
    public static final int DEFAULT_CONNECT_TIMEOUT_MS = 30 * 1000;

    /**
     * 默认的分配缓存空间，单位：字节
     */
    public static final int DEFAULT_BUCKET = 4096;

    /**
     * Map初始容量
     */
    private static final int MAP_INITIAL_CAPACITY = 8;

    /**
     * 发送下载请求
     *
     * @param url   访问链接，a URL String
     * @param local 保存到本地的文件名，包括目录路径
     * @throws IOException 下载失败，错误消息
     */
    public static void download(String url, String local) throws IOException {
        HttpURLConnection urlConn = null;
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        try {
            urlConn = (HttpURLConnection) (new URL(url)).openConnection();
            urlConn.setRequestProperty("Connection", "Keep-Alive");
            urlConn.setRequestMethod("GET");
            urlConn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
            urlConn.connect();

            int statusCode = urlConn.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_OK) {
                in = new BufferedInputStream(urlConn.getInputStream());
                out = new BufferedOutputStream(new FileOutputStream(new File(local)));

                int size;
                byte[] bucket = new byte[DEFAULT_BUCKET];
                while ((size = in.read(bucket)) != -1) {
                    if (size > 0) {
                        out.write(bucket, 0, size);
                        out.flush();
                    }
                }
            } else {
                String errMsg = urlConn.getResponseMessage();
                throw new IOException(errMsg);
            }
        } finally {
            if (out != null) {
                out.close();
            }

            if (in != null) {
                in.close();
            }

            if (urlConn != null) {
                urlConn.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        // 下载网站 => 本地目录
        Map<String, String> paths = new HashMap<>(MAP_INITIAL_CAPACITY);

        paths.put("http://***.com/download?name=晴天.mp3", "mp3/晴天.mp3");
        paths.put("http://***.com/download?name=稻香.mp3", "mp3/稻香.mp3");
        paths.put("http://***.com/download?name=夜曲.mp3", "mp3/夜曲.mp3");
        paths.put("http://***.com/download?name=安静.mp3", "mp3/安静.mp3");
        paths.put("http://***.com/download?name=青花瓷.mp3", "mp3/青花瓷.mp3");
        paths.put("http://***.com/download?name=东风破.mp3", "mp3/东风破.mp3");
        paths.put("http://***.com/download?name=等你下课.mp3", "mp3/等你下课.mp3");
        paths.put("http://***.com/download?name=爱在西元前.mp3", "mp3/爱在西元前.mp3");

        for (Map.Entry<String, String> entry : paths.entrySet()) {
            String url = entry.getKey();
            String local = entry.getValue();

            new Thread(() -> {
                try {
                    download(url, local);
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }).start();
        }
    }

}
