package com.beanpodtech.allinone.utils;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.activity.AlivcPlayerActivity;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.application.EduApplication;
import com.beanpodtech.allinone.bean.AliVideoBean;
import com.beanpodtech.allinone.bean.BuyVideoIdBean;
import com.beanpodtech.allinone.bean.ServiceTimeBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.interfaces.OnSyncServerCallBack;
import com.beanpodtech.allinone.service.TimeCounterService;
import com.beanpodtech.allinone.widget.LoadingView;
import com.lzy.okgo.model.Response;

import java.util.HashMap;

/**
 *
 */
public class PlayVideoUtils {
    private static final String TAG = "VideoAdapter";
    /**
     * 正常视频
     */
    public final static int NORMAL_VIDEO = 1;
    /**
     * 免费体验区
     */
    public final static int FREE_VIDEO = 2;
    /**
     * 学习记录
     */
    public final static int RECOED_VIDEO = 3;
    /**
     * 企业宣传
     */
    public final static int COMPANY_VIDEO = 4;
    /**
     * 推荐课程视频
     */
    public final static int RECOMMEND_VIDEO = 5;
    /**
     * 搜索出来的视频
     */
    public final static int SEARCH_VIDEO = 6;
    /**
     * 是否需要插入到学习记录中
     */
    private boolean isNeedRecord = false;
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 视频Id
     */
    private String videoId;
    /**
     * 课程Id
     */
    private String courseId;
    /**
     * 类型  对应上面
     */
    private int type;
    /**
     * loading
     */
    private LoadingView loadingView;
    /**
     * 单例模式
     **/
    private static PlayVideoUtils playVideoUtils = null;

    private long currentTimeMillis = System.currentTimeMillis();
    /**
     * 直接到的播放时间点
     */
    private long seekToPoint = 0;

    /**
     * 构造函数私有化
     **/
    private PlayVideoUtils() {

    }

    /**
     * 公有的静态函数，对外暴露获取单例对象的接口
     **/
    public static PlayVideoUtils getInstance() {
        if (playVideoUtils == null) {
            synchronized (PlayVideoUtils.class) {
                if (playVideoUtils == null) {
                    playVideoUtils = new PlayVideoUtils();
                }
            }
        }
        return playVideoUtils;
    }

    /**
     * @param videoId 视频Id
     * @return
     */
    public PlayVideoUtils setVideoId(String videoId) {
        this.videoId = videoId;
        return this;
    }

    /**
     * @param seekToPoint 跳转的播放时间点
     * @return
     */
    public PlayVideoUtils setSeekToPoint(long seekToPoint) {
        this.seekToPoint = seekToPoint;
        return this;
    }

    /**
     * @param courseId 课程Id
     * @return
     */
    public PlayVideoUtils setCourseId(String courseId) {
        this.courseId = courseId;
        return this;
    }

    /**
     * @param mContext 上下文
     * @return
     */
    public PlayVideoUtils setContext(Context mContext) {
        this.mContext = mContext;
        return this;
    }

    /**
     * @param isNeedRecord 是否需要插入到学习记录中
     * @return
     */
    public PlayVideoUtils setIsNeedRecord(boolean isNeedRecord) {
        this.isNeedRecord = isNeedRecord;
        return this;
    }

    /**
     * @param type 类型
     * @return
     */
    public PlayVideoUtils setType(int type) {
        this.type = type;
        return this;
    }

    public PlayVideoUtils build() {
        if (mContext != null && !((Activity) mContext).isFinishing()) {
            loadingView = new LoadingView(mContext, R.style.CustomDialog);
            loadingView.setTitle("请稍后...");
            loadingView.show();
        }
        getPlayAuthToPlay();
        return this;
    }

//    /**
//     * @param mContext 上下文
//     * @param videoId  视频Id
//     * @param courseId 课程Id
//     * @param type     类型
//     */
//    public PlayVideoUtils(Context mContext, String videoId, String courseId, int type) {
//        this.mContext = mContext;
//        this.videoId = videoId;
//        this.courseId = courseId;
//        this.type = type;
//
//    }

    public void getPlayAuthToPlay() {
        OkGoBuilder.getInstance()
                .url(UrlConfig.GET_PLAYAUTH)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(AliVideoBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBody(videoId)))
                .callback(new OkGoUtil<AliVideoBean>(AliVideoBean.class) {
                    @Override
                    public void onSuccess(Response<AliVideoBean> response) {
                        if (mContext != null && !((Activity) mContext).isFinishing()) {
                            loadingView.dismiss();
                        }
                        AliVideoBean body = response.body();
                        if (body != null) {
                            //是否属于该卷区
//                    if (!body.isBelongCurrent()) {
//                        ToastUtils.show(mContext, mContext.getString(R.string.currentvideo_notbelong));
//                        return;
//                    }
                            //是否允许播放
                            // TODO: 2020/7/13 后续加试看
                            boolean isTry = !body.isAllowPlay();
                            if (!body.isAllowPlay()) { //  不允许播放
                                ToastUtils.show(EduApplication.getContext(), R.string.not_have_role_watch);
                            } else { // allowPlay
                                if (body.isNeedTiming()) {     //允许播放并且需要计时
                                    //To start prepare work of time counting
                                    TimeCounter timeCounter = TimeCounter.getInstance(mContext);
                                    FileUtil fileUtil = new FileUtil();
                                    byte[] nativeBitmap;
                                    final BuyVideoIdBean[] data = new BuyVideoIdBean[1];
                                    //timeCounter.setBitmapExsitFlag(false);

                                    // 同步时间
                                    HashMap<String, String> map = new HashMap<>();
                                    map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
                                    SyncUtils.getInstance().requestBody(HttpUtils.getRequestJson(map)).callback(new OnSyncServerCallBack() {
                                        @Override
                                        public void onSyncServer(Object object) {
                                            ServiceTimeBean serviceTimeBean = (ServiceTimeBean) object;
                                            if (serviceTimeBean != null) {
                                                if (serviceTimeBean.getStatus() == -1) {
                                                    // TODO: 2020/7/3 禁止使用状态需要处理
                                                    return;
                                                }
                                                if (serviceTimeBean.getDate() >= 1 * 1000 * 1000) {
                                                    currentTimeMillis = serviceTimeBean.getDate();
                                                } else {
                                                    Log.e(TAG, "getPlayAuthToPlay get server time exception, use box time");
                                                }
                                            }
                                        }
                                    }).build(SyncUtils.SERVICETIME);

                                    String fileName = timeCounter.getFileName(SpUtil.getInstace().getString(Contants.USER_NAME, "unknown"),
                                            videoId, currentTimeMillis);
                                    if (fileName == null || fileName.length() < 1) {
                                        Log.e(TAG, "getPlayAuth file name is invalid");
                                        return;
                                    }
//                                if (false && timeCounter.getCurrentFileName() != null && !("".equals(timeCounter.getCurrentFileName()))
//                                        && timeCounter.getCurrentFileName().equals(fileName) && timeCounter.isBitmapExsitFlag()) {
//                                    Log.d(TAG, "Open the same video");
//                                } else {
                                    timeCounter.reset();//判断是否与上次的看的视频一致,通过filename去判断
                                    timeCounter.setCurrentFileName(fileName);
                                    //get natvie bitmap
                                    if (timeCounter.isBitMapFileExist(fileName)) {
                                        nativeBitmap = fileUtil.readFile(fileName);

                                        if (nativeBitmap != null) {
                                            timeCounter.setVideoSecondBitMap(nativeBitmap);
                                            timeCounter.setBitmapExsitFlag(true);
                                            timeCounter.setNativeBitmapExsitFlag(true);
                                        }
                                        //get counter
                                        //SpUtil.getInstace().getInt(fileName, 0);
                                    }
                                    timeCounter.setNativeBitmapCheckState(Contants.BITMAP_CHECK_STATE);
//                                }
                                    timeCounter.setCourseId(courseId);
                                    timeCounter.setVideoId(videoId);
                                    //get remote bitmap for test
                                    TimeCounterService.startService(mContext, TimeCounterService.ACTION_START,
                                            videoId, courseId, 0, null, body.isNeedTiming());
                                }
                            }


                            if (seekToPoint != 0) {
                                AlivcPlayerActivity.startAlivcPlayerActivity(mContext, body, courseId, videoId, isTry, seekToPoint);
                                seekToPoint = 0;
                            } else {
                                AlivcPlayerActivity.startAlivcPlayerActivity(mContext, body, courseId, videoId, isTry, 0);
                            }
                        } else {
                            ToastUtils.show(mContext, "网络异常");
                        }
                    }

                    @Override
                    public void onError(Response<AliVideoBean> response) {
                        loadingView.dismiss();
                        super.onError(response);
                    }
                }).build();
    }

    private HashMap<String, String> getRequestBody(String videoId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("courseId", courseId);
        if (isNeedRecord) {
            map.put("type", "1");
        }

        return map;
    }
}
