package com.zlm.hp.manager;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;

import com.zlm.down.entity.DownloadTask;
import com.zlm.down.entity.DownloadThreadInfo;
import com.zlm.down.interfaces.IDownloadTaskEvent;
import com.zlm.down.manager.DownloadTaskManager;
import com.zlm.hp.constants.ConfigInfo;
import com.zlm.hp.constants.ResourceConstants;
import com.zlm.hp.db.util.DownloadThreadInfoDB;
import com.zlm.hp.db.util.VideoInfoDB;
import com.zlm.hp.entity.VideoInfo;
import com.zlm.hp.http.APIHttpClient;
import com.zlm.hp.receiver.AppSystemReceiver;
import com.zlm.hp.receiver.AudioBroadcastReceiver;
import com.zlm.hp.util.CodeLineUtil;
import com.zlm.hp.util.HttpUtil;
import com.zlm.hp.util.ResourceUtil;
import com.zlm.hp.util.ZLog;

import java.util.Date;

/**
 * @Description: 在线视频管理
 * @author: zhangliangming
 * @date: 2019-01-06 0:28
 **/
public class OnLineVideoManager {

    /**
     * 子线程用于执行耗时任务
     */
    private Handler mWorkerHandler;
    //创建异步HandlerThread
    private HandlerThread mHandlerThread;

    /**
     * 线程个数
     */
    public static final int mThreadNum = 10;
    /**
     * 当前任务id
     */
    private String mCurTaskId = "-1";

    /**
     * 下载管理器
     */
    private static DownloadTaskManager mDownloadTaskManager;

    /**
     *
     */
    private static Context mContext;

    /**
     * 正在播放
     */
    public static final int PLAYING = 0;
    /**
     * 暂停
     */
    public static final int PAUSE = 1;

    /**
     * 停止
     */
    public static final int STOP = 2;

    /**
     * 正在播放
     */
    public static final int PLAYINGNET = 3;

    /**
     * seekto
     */
    public static final int SEEKTO = 4;

    /**
     * 当前播放状态
     */
    private int mPlayStatus = STOP;

    public OnLineVideoManager(Context context) {

        this.mContext = context;
        //创建异步HandlerThread
        mHandlerThread = new HandlerThread("onlineDownloadVideoTaskThread", Process.THREAD_PRIORITY_BACKGROUND);
        //必须先开启线程
        mHandlerThread.start();
        //子线程Handler
        mWorkerHandler = new Handler(mHandlerThread.getLooper());

        mDownloadTaskManager = new DownloadTaskManager(context, "onlineDownloadVideoTaskManager", new IDownloadTaskEvent() {
            @Override
            public void taskWaiting(DownloadTask task) {

            }

            @Override
            public void taskDownloading(DownloadTask task, int downloadedSize) {

                ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task taskDownloading ->" + task.getTaskName() + " " + downloadedSize);
                //更新在线缓存进度
                AudioBroadcastReceiver.sendDownloadingOnlineVideoReceiver(mContext, task);
                //处理下载视频
                handleDondloadNetVideo(task, downloadedSize);

            }

            @Override
            public void taskPause(DownloadTask task, int downloadedSize) {

                ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task taskPause ->" + task.getTaskName() + " " + downloadedSize);
            }

            @Override
            public void taskCancel(DownloadTask task) {
                ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task taskCancel ->" + task.getTaskName());
            }

            @Override
            public void taskFinish(DownloadTask task, int downloadedSize) {

                if (mCurTaskId.equals(task.getTaskId())) {
                    //任务完成后，重置任务id
                    mCurTaskId = "-1";
                }
                //更新在线缓存进度
                AudioBroadcastReceiver.sendDownloadingOnlineVideoReceiver(mContext, task);
                ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task taskFinish ->" + task.getTaskName() + " " + downloadedSize);
                //完成
                AudioBroadcastReceiver.sendDownloadedOnlineVideoReceiver(mContext, task);
            }

            @Override
            public void taskError(DownloadTask task, String msg) {
                if (mCurTaskId.equals(task.getTaskId())) {
                    //任务完成后，重置任务id
                    mCurTaskId = "-1";
                }
                ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task taskError ->" + task.getTaskName());
                AppSystemReceiver.sendToastErrorMsgReceiver(mContext, msg);

                //停止播放
                AudioBroadcastReceiver.sendOnlineVideoStopReceiver(mContext, task);
            }

            @Override
            public boolean getAskWifi() {
                ConfigInfo configInfo = ConfigInfo.obtain();
                return configInfo.isWifi();
            }

            @Override
            public int getTaskThreadDownloadedSize(DownloadTask task, int threadId) {
                if (DownloadThreadInfoDB.isExists(mContext, task.getTaskId(), mThreadNum, threadId)) {
                    //任务存在
                    DownloadThreadInfo downloadThreadInfo = DownloadThreadInfoDB.getDownloadThreadInfo(mContext, task.getTaskId(), mThreadNum, threadId);
                    if (downloadThreadInfo != null) {
                        ZLog.d(new CodeLineUtil().getCodeLineInfo(), "task getTaskThreadDownloadedSize -> 在线播放任务名称：" + task.getTaskName() + " 子任务线程id: " + threadId + " 已下载大小：" + downloadThreadInfo.getDownloadedSize());
                        return downloadThreadInfo.getDownloadedSize();
                    }
                }
                return 0;
            }

            @Override
            public void taskThreadDownloading(DownloadTask task, int threadId, int downloadedSize) {

                DownloadThreadInfo downloadThreadInfo = new DownloadThreadInfo();
                downloadThreadInfo.setDownloadedSize(downloadedSize);
                downloadThreadInfo.setThreadId(threadId);
                downloadThreadInfo.setTaskId(task.getTaskId());
                downloadThreadInfo.setThreadNum(mThreadNum);

                if (DownloadThreadInfoDB.isExists(mContext, task.getTaskId(), mThreadNum, threadId)) {
                    //任务存在
                    DownloadThreadInfoDB.update(mContext, task.getTaskId(), mThreadNum, threadId, downloadedSize);
                } else {
                    //任务不存在
                    DownloadThreadInfoDB.add(mContext, downloadThreadInfo);
                }
            }

            @Override
            public void taskThreadPause(DownloadTask task, int threadId, int downloadedSize) {

            }

            @Override
            public void taskThreadFinish(DownloadTask task, int threadId, int downloadedSize) {

                //防止有些比较小的歌曲在1s内下载完成，没有调用downloading的接口

                DownloadThreadInfo downloadThreadInfo = new DownloadThreadInfo();
                downloadThreadInfo.setDownloadedSize(downloadedSize);
                downloadThreadInfo.setThreadId(threadId);
                downloadThreadInfo.setTaskId(task.getTaskId());
                downloadThreadInfo.setThreadNum(mThreadNum);
                if (DownloadThreadInfoDB.isExists(mContext, task.getTaskId(), mThreadNum, threadId)) {
                    //任务存在
                    DownloadThreadInfoDB.update(mContext, task.getTaskId(), mThreadNum, threadId, downloadedSize);
                } else {
                    //任务不存在
                    DownloadThreadInfoDB.add(mContext, downloadThreadInfo);
                }

                //更新
                if (VideoInfoDB.isVideoExists(mContext, task.getTaskId())) {
                    VideoInfoDB.updateVideo(mContext, task.getTaskId(), VideoInfo.STATUS_FINISH);
                }

                //处理下载视频
                handleDondloadNetVideo(task, downloadedSize);
            }

            @Override
            public void taskThreadError(DownloadTask task, int threadId, String msg) {

            }
        });
    }

    /**
     * 处理下载视频
     *
     * @param task
     * @param downloadedSize
     */
    private void handleDondloadNetVideo(DownloadTask task, int downloadedSize) {
        if (mPlayStatus == PLAYINGNET && downloadedSize > 1024 * 1024) {
            mPlayStatus = PLAYING;
            AudioBroadcastReceiver.sendPlayNetVideoReceiver(mContext, task);
        }
    }


    /**
     * 添加任务
     *
     * @param videoInfo
     */
    public synchronized void addDownloadTask(final VideoInfo videoInfo) {
        //暂停旧的任务
        pauseTask();

        mCurTaskId = videoInfo.getHash();
        //异步下载
        mWorkerHandler.post(new Runnable() {
            @Override
            public void run() {
                addTask(videoInfo);
            }
        });


    }

    /**
     * @param videoInfo
     */
    private void addTask(VideoInfo videoInfo) {

        APIHttpClient apiHttpClient = HttpUtil.getHttpClient();
        ConfigInfo configInfo = ConfigInfo.obtain();

        apiHttpClient.getMVInfo(mContext, videoInfo.getHash(), videoInfo, configInfo.isWifi());

        DownloadTask downloadTask = new DownloadTask();
        downloadTask.setTaskName(videoInfo.getMvName());
        downloadTask.setTaskExt(videoInfo.getFileExt());
        downloadTask.setTaskId(videoInfo.getHash());

        String fileName = videoInfo.getTitle();
        String taskPath = ResourceUtil.getFilePath(mContext, ResourceConstants.PATH_VIDEO, fileName + "." + downloadTask.getTaskExt());
        //String taskTempPath = ResourceUtil.getFilePath(mContext, ResourceConstants.PATH_VIDEO_TEMP, videoInfo.getHash() + ".temp");
        //downloadTask.setTaskPath(taskPath);
        downloadTask.setTaskTempPath(taskPath);
        downloadTask.setTaskUrl(videoInfo.getDownloadUrl());
        downloadTask.setThreadNum(mThreadNum);
        downloadTask.setCreateTime(new Date());

        //添加
        if (!VideoInfoDB.isVideoExists(mContext, videoInfo.getHash())) {
            VideoInfoDB.addVideoInfo(mContext, videoInfo);
        }

        mDownloadTaskManager.addDownloadTask(downloadTask);
    }

    /**
     * 暂停任务
     *
     * @param
     */
    public synchronized void pauseTask() {
        //暂停旧的任务
        if (!mCurTaskId.equals("-1")) {
            mDownloadTaskManager.pauseDownloadTask(mCurTaskId);
        }
    }

    public int getPlayStatus() {
        return mPlayStatus;
    }

    public void setPlayStatus(int playStatus) {
        this.mPlayStatus = playStatus;
    }

    /**
     * 释放
     */
    public void release() {

        mDownloadTaskManager.release();

        //移除队列任务
        if (mWorkerHandler != null) {
            mWorkerHandler.removeCallbacksAndMessages(null);
        }

        //关闭线程
        if (mHandlerThread != null)
            mHandlerThread.quit();
    }
}
