package com.reptileclient.jlifeapp.util.page;

import com.reptileclient.jlifeapp.util.email.EmailUtils;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class DownloadUtil {
    //资源路径
    private String path;
    //文件保存位置
    private String targetFile;
    //监听下载状态
    private OnDownloadListener onDownloadListener;


    private static Set<Integer> processSet = new HashSet<>();

    public static DownloadUtil getInstance(String path, String targetFile, OnDownloadListener onDownloadListener) {
        return new DownloadUtil(path, targetFile, onDownloadListener);

    }

    public static DownloadUtil getInstance(String path, String targetFile) {
        return getInstance(path, targetFile, new DefaultDOwnLoadListener());

    }

    //构造函数
    private DownloadUtil(final String path, final String targetFile, final OnDownloadListener onDownloadListener) {
        this.path = path;
        this.targetFile = targetFile;
        this.onDownloadListener = onDownloadListener;
    }

    //下载
    public void download() throws IOException {
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

        okhttp3.Request request = new Request.Builder()
                .get()
                .url(path)
                .build();
        Call call = client.newCall(request);
        String dir = EmailUtils.getFileDir();
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //下载失败回调
                onDownloadListener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //判断连接是否成功
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    //创建本地文件
                    File outFile = new File(targetFile);
                    //判断文件是否存在 不存在则新建
                    if (!outFile.getParentFile().exists()) {
                        outFile.mkdirs();
                    }
                    if (!outFile.exists()) {
                        outFile.createNewFile();
                    }
                    //创建文件输出流
                    FileOutputStream fos = new FileOutputStream(outFile);
                    //创建输入流
                    InputStream inputStream = null;
                    //判断请求数据是否为null
                    if (response.body() != null) {
                        //获取InputStream实例
                        inputStream = response.body().byteStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        //读取网络数据
                        while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        //写入文件
                        fos.flush();
                    }
                    fos.close();
                    //下载成功回调
                    onDownloadListener.onDownloadSuccess();
                    //写一个下载成功的文件到当前路径下
                    try (FileWriter fw = new FileWriter(dir + ".success")) {
                        fw.write("success");
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                    response.close();
                }

            }
        });


    }


    /**
     * 下载状态回调接口
     */
    public interface OnDownloadListener {
        //下载成功
        void onDownloadSuccess();


        //下载失败
        void onDownloadFailed(Exception e);
    }

    public static class DefaultDOwnLoadListener implements OnDownloadListener {

        @Override
        public void onDownloadSuccess() {
            processSet.clear();
            System.out.println("下载成功");
        }


        @Override
        public void onDownloadFailed(Exception e) {
            processSet.clear();
            System.out.println("下载失败，失败原因：" + e.getMessage());
        }
    }
}
