package com.efounder.chat.http.download;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.db.FileEntity;
import com.efounder.chat.http.OKHttpUtils;
import com.efounder.chat.utils.DialogUtil;
import com.efounder.chat.utils.ThreadPoolUtils;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.AppContext;
import com.efounder.utils.ResStringUtil;
import com.pansoft.library.utils.NetUtil;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;

/**
 * Created by zhangshunyun on 2017/7/13.
 * 文件下载管理类
 */

public class DownloadManager {

    // private Context mContext;
    private DownloadTask task;
    private OKHttpUtils.DownLoadCallBack listener;
    public Handler handler = new Handler();
    public static HashMap<String, Call> downCalls = new HashMap<>();//用来存放各个下载的请求
    public static ArrayList<DownloadTaskObserve> OBSERVES = new ArrayList<>();
    public static HashMap<String, DownloadInfo> DOWNLOAD_INFO_HASHMAP = new HashMap<>();
    private static DownloadManager instance = new DownloadManager();
    private DownloadInfo downloadInfo;


    public static DownloadManager getInstance() {
        return instance;
    }

    public void removeObserve(DownloadTaskObserve observe) {
        OBSERVES.remove(observe);
    }

    public void addObserve(DownloadTaskObserve observe) {
        OBSERVES.add(observe);
    }

    public void addDownloadListener(OKHttpUtils.DownLoadCallBack listener) {
        this.listener = listener;
    }

    public void removeDownLoadListener() {
        this.listener = null;
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    public void addDownloadInfo(String messageID, DownloadInfo info) {
        DOWNLOAD_INFO_HASHMAP.put(messageID, info);
    }

    public void notifyObserves(final String appId) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                for (DownloadTaskObserve item : OBSERVES) {
                    item.update(appId);
                }
            }
        });
    }

    public void notifyObservesDownload(final String messageID) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.downLoadCallBack(messageID);
                }


            }
        });
    }

    /**
     * 下载
     *
     * @param id
     * @param url
     * @param fileName
     * @param desFilePath
     * @param cloudBaseUrl
     */
    public void download(Context mContext, final String id, final String url, final String fileName,
                         final String desFilePath, final String cloudBaseUrl, final IMStruct002 imStruct002) {
        if (!NetUtil.isNetAvailable(AppContext.getInstance())) {
            Toast.makeText(AppContext.getInstance(), mContext.getResources().getString(R.string.common_text_please_check_your_network), Toast.LENGTH_SHORT).show();
        } else if (downloadInfo.downloadOnGPRS || NetUtil.isWIFIActivate(AppContext.getInstance())) {
            downloadAfterJudge(id, url, fileName, desFilePath, cloudBaseUrl, imStruct002);
        } else {
            DialogUtil.showDialog(mContext, ResStringUtil.getString(R.string.mobilecomps_dataman),
                    ResStringUtil.getString(R.string.mobilecomps_dataman1), ResStringUtil.getString(R.string.common_text_continue), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            downloadInfo.downloadOnGPRS = true;
                            downloadAfterJudge(id, url, fileName, desFilePath, cloudBaseUrl, imStruct002);

                        }
                    }, ResStringUtil.getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            downloadInfo.downloadOnGPRS = false;
                        }
                    });
        }

    }

    private void downloadAfterJudge(String id, String url, String fileName, String desFilePath,
                                    String cloudBaseUrl, IMStruct002 imStruct002) {
        task = new DownloadTask(id, url, fileName, desFilePath, cloudBaseUrl, imStruct002);
        boolean execute = ThreadPoolUtils.execute(task);
        if (!execute) {
            // 等待下载
            task.setState(State.DOWNLOAD_WAIT);
        }
    }

    /**
     * 任务在等待状态下 删除下载任务
     *
     * @param id
     */
    public void deleteQueueTask(String id) {
        DownloadInfo downloadInfo = DOWNLOAD_INFO_HASHMAP.get(id);
        boolean cancelWaitTask = ThreadPoolUtils.cancelWaitTask(id);
        if (cancelWaitTask) {
            downloadInfo.state = State.DOWNLOAD_NOT;
//            notifyObserves(id);
            notifyObservesDownload(id);
            //    DOWNLOAD_INFO_HASHMAP.remove(id);
        }
//        FileEntity.saveEntityByAppId(downloadInfo, mContext);
        FileEntity.deleteEntity(downloadInfo, AppContext.getInstance());
    }

    /**
     * 退出后 取消下载
     */
//    public void cancelTask() {
//        for (int i = 0; i < urlList.size(); i++) {
//            if (null != task) {
//                task.cancel(urlList.get(i));
//                deleteQueueTask(idList.get(i));
//            }
//        }
//        if (DOWNLOAD_INFO_HASHMAP.size() != 0) {
//            DOWNLOAD_INFO_HASHMAP.clear();
//        }
//    }


    /**
     * 设置当前状态
     *
     * @param id
     * @param state
     */
    public void setState(String id, int state) {
        DOWNLOAD_INFO_HASHMAP.get(id).state = state;
    }

    /**
     * 处理点击事件
     *
     * @param id           messageID
     * @param context
     * @param url
     * @param fileName
     * @param desFilePath
     * @param cloudBaseUrl
     */
    public void handleClick(String id, Context context, String url, String fileName, String desFilePath, String cloudBaseUrl,
                            IMStruct002 imStruct002) {
        //this.mContext = context;
        downloadInfo = DOWNLOAD_INFO_HASHMAP.get(id);
//        addInformation(id, url, fileName, desFilePath);
        if (downloadInfo == null) {
            return;
        }
        switch (downloadInfo.state) {
            case State.DOWNLOAD_COMPLETED:
                // 已经下载完成
                break;
            case State.DOWNLOAD_STOP:
                // 暂停
            case State.DOWNLOAD_ERROR:
                // 出错，重试
            case State.DOWNLOAD_NOT:
                // 未下载
                DownloadManager.getInstance().download(context, downloadInfo.messageID, url, fileName, desFilePath, cloudBaseUrl,
                        imStruct002);
                break;
            case State.DOWNLOAD_WAIT:
                // 线程池已满，应用添加到等待队列，用户点击后取消下载
                DownloadManager.getInstance().deleteQueueTask(downloadInfo.messageID);
                break;
            case State.DOWNLOADING:
                // 未出现异常，显示下载进度，点击暂停
                DownloadManager.getInstance().setState(downloadInfo.messageID, State.DOWNLOAD_STOP);
                break;

        }
    }

    /**
     * 将下载文件的信息存入集合中
     *
     * @param id
     * @param url
     * @param fileName
     * @param desFilePath
     */
//    private void addInformation(String id, String url, String fileName, String desFilePath) {
//        urlList.add(url);
//        idList.add(id);
//        fileNameList.add(fileName);
//        desFilePathList.add(desFilePath);
//    }
}
