package com.gensee.fastsdkdemo;

import android.content.Context;

import com.gensee.download.ErrorCode;
import com.gensee.download.VodDownLoadEntity;
import com.gensee.download.VodDownLoader;
import com.gensee.entity.ChatMsg;
import com.gensee.entity.InitParam;
import com.gensee.entity.QAMsg;
import com.gensee.entity.VodObject;
import com.gensee.taskret.OnTaskRet;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.StringUtil;
import com.gensee.vod.VodSite;

import java.util.List;

public class VodDownloadManager implements VodDownLoader.OnDownloadListener , VodSite.OnVodListener {

    private static final String TAG = "VodDownloadManager";
    private VodSite vodSite;
    private VodDownLoader mDownloader;
    private DownloadUIListener uiCallBack;
    private static VodDownloadManager ins = null;
    private List<VodDownLoadEntity> list;
    public static VodDownloadManager getIns(){
        if(ins == null){
            synchronized (VodDownloadManager.class){
                if(ins == null){
                    ins = new VodDownloadManager();
                }
            }
        }
        return ins;
    }

    public void initDownLoader(Context context){
        VodSite.init(context, new OnTaskRet() {

            @Override
            public void onTaskRet(boolean arg0, int arg1, String arg2) {

            }
        });
        //只初始化一个下载器，回调
        if(mDownloader == null){
            //如果需要区分多用户，请使用带用户id的instance进行初始化，默认情况下用户id为0
            mDownloader = VodDownLoader.instance(context,this,null);
        }
        // 启动已存在且未完成的任务
        mDownloader.download();
    }


    public int download(String downloadId){
        if(mDownloader != null){
            return  mDownloader.download(downloadId);
        }
        return ErrorCode.FAILED;
    }

    public void stop(String downLoadId) {
        if(mDownloader != null){
            mDownloader.stop(downLoadId);
        }
    }

    public void delete(String downLoadId) {
        if(mDownloader != null){
            mDownloader.delete(downLoadId);
        }
    }


    public void setUICallback(DownloadUIListener uiCallBack){
        this.uiCallBack = uiCallBack;
    }

    @Override
    public void onDLFinish(String downLoadId, String localPath) {
        GenseeLog.i(TAG, "onDLFinish downLoadId = " + downLoadId + " uiCallback = " + uiCallBack);
        if(uiCallBack != null){
            uiCallBack.onDLFinish(downLoadId,localPath);
        }
    }

    @Override
    public void onDLPosition(String downLoadId, int percent) {
        GenseeLog.i(TAG, "onDLPosition downLoadId = " + downLoadId
                + " percent = " + percent + " uiCallback = " + uiCallBack);
        if(uiCallBack != null){
            uiCallBack.onDLPosition(downLoadId,percent);
        }
    }

    public void onDLPrepare(String downLoadId) {
        GenseeLog.i(TAG, "onDLPrepare downLoadId = " + downLoadId+ " uiCallback = " + uiCallBack);
      if(uiCallBack != null){
          uiCallBack.onDLPrepare(downLoadId);
      }
    }

    @Override
    public void onDLStart(String downLoadId) {
        GenseeLog.i(TAG, "onDLStart downLoadId = " + downLoadId + " uiCallback = " + uiCallBack);
        if(uiCallBack != null){
            uiCallBack.onDLStart(downLoadId);
        }
    }

    @Override
    public void onDLStop(String downLoadId) {
        // 下载停止
        GenseeLog.i(TAG, "onDLStop downLoadId = " + downLoadId +  " uiCallback = " + uiCallBack);
        if(uiCallBack != null){
            uiCallBack.onDLStop(downLoadId);
        }

    }

    @Override
    public void onDLError(String downLoadId, int errorCode) {
        GenseeLog.i(TAG, "onDLError downLoadId = " + downLoadId
                + " errorCode = " + errorCode + " uiCallback = " + uiCallBack);
       if(uiCallBack != null){
           uiCallBack.onDLError(downLoadId,errorCode);
       }
    }

    @Override
    public void onRecordInfo(String s, long l, long l1, long l2) {

    }

    public List<VodDownLoadEntity> getDownloadList() {
        list =  mDownloader == null?null:mDownloader.getDownloadList();
        return list;
    }

    public void setAutoDownloadNext(boolean autoDownloadNext) {
        if(mDownloader != null){
            mDownloader.setAutoDownloadNext(autoDownloadNext);
        }
    }

    public void addDownload(InitParam initParam,Context context){
        if(initParam == null || context == null){
            return;
        }
        //传过来的liveid也是点播id，也是downloadid
        String vodId = initParam.getLiveId();
        if(!StringUtil.isEmpty(vodId)&& isInQuene(vodId)){
            //当使用点播id进行下载情况下，判断id在队列中，就不需要再进行初始化该点播
            return;
        }
        initParam.setDownload(true);
        if(vodSite != null){
            vodSite.setVodListener(null);
        }
        vodSite = new VodSite(context);
        vodSite.setVodListener(this);
        vodSite.getVodObject(initParam);
    }

    /********************* OnVodListener **************************/


    /**
     * 聊天记录 getChatHistory 响应 vodId 点播id list 聊天记录
     */
    @Override
    public void onChatHistory(String vodId, List<ChatMsg> list, int pageIndex, boolean more) {
        GenseeLog.d(TAG, "onChatHistory vodId = " + vodId + " " + list);
        // ChatMsg msg;
        // msg.getContent();//消息内容
        // msg.getSenderId();//发送者用户id
        // msg.getSender();//发送者昵称
        // msg.getTimeStamp();//发送时间，单位毫秒
    }

    /**
     * 问答记录 getQaHistory 响应 list 问答记录 vodId 点播id
     */
    @Override
    public void onQaHistory(String vodId, List<QAMsg> list, int pageIndex, boolean more) {
        GenseeLog.d(TAG, "onQaHistory vodId = " + vodId + " " + list);
        if (more) {
            // 如果还有更多的历史，还可以继续获取记录（pageIndex+1）页的记录
        }
        // QAMsg msg;
        // msg.getQuestion();//问题
        // msg.getQuestId();//问题id
        // msg.getQuestOwnerId();//提问人id
        // msg.getQuestOwnerName();//提问人昵称
        // msg.getQuestTimgstamp();//提问时间 单位毫秒
        //
        // msg.getAnswer();//回复的内容
        // msg.getAnswerId();//“本条回复”的id 不是回答者的用户id
        // msg.getAnswerOwner();//回复人的昵称
        // msg.getAnswerTimestamp();//回复时间 单位毫秒
    }


    /**
     * 获取点播详情
     */
    @Override
    public void onVodDetail(VodObject vodObj) {
        GenseeLog.d(TAG, "onVodDetail " + vodObj);
        if (vodObj != null) {
            vodObj.getDuration();// 时长
            vodObj.getEndTime();// 录制结束时间 始于1970的utc时间毫秒数
            vodObj.getStartTime();// 录制开始时间 始于1970的utc时间毫秒数
            vodObj.getStorage();// 大小 单位为Byte
        }
    }

    // int ERR_DOMAIN = -100; // ip(domain)不正确
    // int ERR_TIME_OUT = -101; // 超时
    // int ERR_UNKNOWN = -102; // 未知错误
    // int ERR_SITE_UNUSED = -103; // 站点不可用
    // int ERR_UN_NET = -104; // 无网络
    // int ERR_DATA_TIMEOUT = -105; // 数据过期
    // int ERR_SERVICE = -106; // 服务不正确
    // int ERR_PARAM = -107; // 参数不正确
    // int ERR_PARAM = -107; // 参数不正确
    // int ERR_THIRD_CERTIFICATION_AUTHORITY //第三方认证失败
    // int ERR_UN_INVOKE_GETOBJECT = -201; //没有调用getVodObject
    // int ERR_VOD_INTI_FAIL = 14; //点播getVodObject失败
    // int ERR_VOD_NUM_UNEXIST = 15; //点播编号不存在或点播不存在
    // int ERR_VOD_PWD_ERR = 16; //点播密码错误
    // int ERR_VOD_ACC_PWD_ERR = 17; //帐号或帐号密码错误
    // int ERR_UNSURPORT_MOBILE = 18; //不支持移动设备
    @Override
    public void onVodErr(final int errCode) {
        String msg = getErrMsg(errCode);
        if(uiCallBack != null){
            uiCallBack.onVodErr(msg);
        }
        GenseeLog.d(TAG,"onVodErr msg = " + msg);
    }

    private boolean isInQuene(String vodId) {
        return mDownloader != null && mDownloader.getDownload(vodId) != null;
    }

    /**
     * getVodObject的响应，vodId 接下来可以下载后播放
     */
    @Override
    public void onVodObject(String vodId) {
        if (!isInQuene(vodId)) {
            setAutoDownloadNext(true);
            int ret = download(vodId);
            GenseeLog.d(TAG, "onVodObject vodId = " + vodId + " ret = " + ret);
            if (uiCallBack != null) {
                uiCallBack.onAddDownload(ret);
            }
        }
    }

    /**
     * 错误码处理,开发者请注意对照自己的app业务给出自己的提示，这里的提示方便调试
     *
     * @param errCode
     *            错误码
     * @return 错误码文字表示内容
     */
    private String getErrMsg(int errCode) {
        String msg = "";
        switch (errCode) {
            case ERR_DOMAIN:
                msg = "domain 不正确";
                break;
            case ERR_TIME_OUT:
                msg = "超时";
                break;
            case ERR_SITE_UNUSED:
                msg = "站点不可用";
                break;
            case ERR_UN_NET:
                msg = "无网络请检查网络连接";
                break;
            case ERR_DATA_TIMEOUT:
                msg = "数据过期";
                break;
            case ERR_SERVICE:
                msg = "请检查填写的serviceType";
                break;
            case ERR_PARAM:
                msg = "请检查参数";
                break;
            case ERR_UN_INVOKE_GETOBJECT:
                msg = "请先调用getVodObject";
                break;
            case ERR_VOD_INTI_FAIL:
                msg = "调用getVodObject失败";
                break;
            case ERR_VOD_NUM_UNEXIST:
                msg = "点播编号不存在或点播不存在";
                break;
            case ERR_VOD_PWD_ERR:
                msg = "点播密码错误";
                break;
            case ERR_VOD_ACC_PWD_ERR:
                msg = "登录帐号或登录密码错误";
                break;
            case ERR_UNSURPORT_MOBILE:
                msg = "不支持移动设备";
                break;
            default:
                break;
        }
        return msg;
    }


    public interface DownloadUIListener extends VodDownLoader.OnDownloadListener{
        void onVodErr(String msg);//点播初始化错误通知
        void onAddDownload(int result);//添加任务
    }
}
