package com.rv.im.mucfile;

import android.os.Environment;
import android.text.TextUtils;

import com.rv.im.db.table.ChatMessage;

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.util.HashMap;
import java.util.Map;

/**
 * @author liuxuan
 * @time 2017-7-7 14:39:11
 * @des 下载管理器，核心下载逻辑
 */
public class RvDownManager {


    private Map<String, Runnable> tasks = new HashMap<>();
    private Map<String, DownListener> listeners = new HashMap<>();

    public interface DownListener {
        void downSuccess();

        void downFailure();
    }

    private RvDownManager() {
//        downDao = DownDao.getInstance(ImSetting.getContext());
    }

    private volatile static RvDownManager instance;
//    private DownDao downDao = null;

    public static RvDownManager instance() {
        if (instance == null) {
            synchronized (RvDownManager.class) {
                if (instance == null) {
                    instance = new RvDownManager();
                }
            }
        }
        return instance;
    }

    // 下载任务
    public void download(ChatMessage message, DownListener listener) {  // 下载 和 断点继续
        DownLoadTask downLoadTask = new DownLoadTask(message);
        tasks.put(message.getContent(), downLoadTask);
        listeners.put(message.getContent(), listener);
        ThreadPoolProxy.getInstance().execute(downLoadTask);
    }


    class DownLoadTask implements Runnable {
        ChatMessage message;

        public DownLoadTask(ChatMessage message) {
            this.message = message;
        }

        @Override
        public void run() {
//            notifyObservers(message);
            HttpURLConnection urlConnection = null;
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            DownListener listener = listeners.get(message.getContent());
            try {
                URL url = new URL(message.getContent());
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(30000);
                urlConnection.setRequestMethod("GET");
                // 设置下载位置
//                    urlConnection.setRequestProperty("Range", "bytes=" + mInfo.cur + "-" + mInfo.max);
                // 设置文件写入位置
                int start = message.getContent().lastIndexOf("/");
                String name = message.getContent().substring(start + 1).toLowerCase();
                File file = new File(getFileDir(), name);
                int code = urlConnection.getResponseCode();
                if (code == 200) {
                    outputStream = new FileOutputStream(file);
                    // 获得文件流
                    inputStream = urlConnection.getInputStream();
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    if (listener != null) {
                        message.setFilePath(file.getAbsolutePath());
                        DownLoadTask task = (DownLoadTask) tasks.get(message.getContent());
                        tasks.remove(task);
                        listener.downSuccess();
                    }

                } else {
                    if (listener != null) {
                        listener.downFailure();
                        DownLoadTask task = (DownLoadTask) tasks.get(message.getContent());
                        tasks.remove(task);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                if (listener != null) {
                    listener.downFailure();
                    DownLoadTask task = (DownLoadTask) tasks.get(message.getContent());
                    tasks.remove(task);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public String getFileDir() {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mucDown");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    /**
     * 取消下载
     */
    public void cancel(ChatMessage message) {
        DownLoadTask task = (DownLoadTask) tasks.get(message.getContent());
        ThreadPoolProxy.getInstance().removeTask(task);
        tasks.remove(task);
    }

    /**
     * 删除文件
     */
    public void detele(ChatMessage message) {
        // 删除文件
        if (!TextUtils.isEmpty(message.getFilePath())) {
            File file = new File(message.getFilePath());
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /*=============== 自定义观察者设计模式  begin ===============*/
//    public interface DownLoadObserver {
//        void onDownLoadInfoChange(DownBean info);
//    }
//
//    List<DownLoadObserver> downLoadObservers = new LinkedList<DownLoadObserver>();
//
//    /**
//     * 添加观察者
//     */
//    public void addObserver(DownLoadObserver observer) {
//        if (observer == null) {
//            throw new NullPointerException("observer == null");
//        }
//        synchronized (this) {
//            if (!downLoadObservers.contains(observer))
//                downLoadObservers.add(observer);
//        }
//    }
//
//    /**
//     * 删除观察者
//     */
//    public synchronized void deleteObserver(DownLoadObserver observer) {
//        downLoadObservers.remove(observer);
//    }
//
//    /**
//     * 通知观察者数据改变
//     */
//    public void notifyObservers(ChatMessage info) {
//        Message msg = new Message();
//        msg.obj = info;
//        msg.what = 200;
//        mHandler.sendMessage(msg);
//    }
//
//    @SuppressLint("HandlerLeak")
//    Handler mHandler = new Handler() {
//        @Override
//        public void dispatchMessage(Message msg) {
//            super.dispatchMessage(msg);
//            if (msg.what == 200) {
//                for (DownLoadObserver observer : downLoadObservers) {
//                    DownBean info = (DownBean) msg.obj;
//                    observer.onDownLoadInfoChange(info);
//                }
//            }
//        }
//    };
}
