package com.beanpodtech.allinone.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.beanpodtech.allinone.application.EduApplication;
import com.beanpodtech.allinone.bean.AnycPlayingTimeBean;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.beanpodtech.allinone.bean.BuyVideoIdBean;
import com.beanpodtech.allinone.interfaces.OnSyncServerCallBack;
import com.beanpodtech.allinone.jni.CounterNative;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.utils.SyncUtils;
import com.beanpodtech.allinone.utils.TimeCounter;

import android.util.Base64;

import java.math.BigDecimal;
import java.util.HashMap;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class TimeCounterService extends IntentService {
    public static final String ACTION_BASE = "com.beanpodtech.allinoneoxclient.service.action";
    public static final String EXTRA_BASE = "com.beanpodtech.allinone.service.extra";
    public static final String TAG = "TimeCounterService";
    /**
     * 接受默认值
     */
    public static final int DEFAULT_PLAYINGTIME = -1;
    private TimeCounter timeCounter;

    /**
     * @param playingTime 单位  毫秒
     */
    public static void startService(Context context, String action, String videoId, String courseId, int playingTime, byte[] bitmap, boolean isNeedTiming) {
        Intent intent = new Intent(context, TimeCounterService.class);
        intent.putExtra(EXTRA_VIDEOID, videoId);
        intent.putExtra(EXTRA_COURSEID, courseId);
        intent.putExtra(EXTRA_PLAYINGTIME, playingTime);
        intent.putExtra(EXTRA_BITMAP, bitmap);
        intent.putExtra(EXTRA_ISNEEDTIMING, isNeedTiming);
        intent.setAction(action);
        context.startService(intent);
    }

//    public static void startService(Context context, String action, int param1, int param2) {
//        Intent intent = new Intent(context, TimeCounterService.class);
//        intent.putExtra(EXTRA_PARAM1, param1);
//        intent.putExtra(EXTRA_PARAM2, param2);
//        intent.setAction(action);
//        context.startService(intent);
//    }

    /**
     * 视频开始
     */
    public static final String ACTION_START = ACTION_BASE + "com.beanpodtech.allinone.service.action.STRAT";

    /**
     * 到60S传一次
     */
    public static final String ACTION_TIME_UP = "com.beanpodtech.allinone.service.action.TIME_UP";
    /**
     * 暂停
     */
    public static final String ACTION_PAUSE = "com.beanpodtech.allinone.service.action.PAUSE";
    /**
     * 关闭播放页面时
     */
    public static final String ACTION_CLOSED = "com.beanpodtech.allinone.service.action.CLOSED";
    /**
     * 播放完成
     */
    public static final String ACTION_COMPLETE = "com.beanpodtech.allinone.service.action.COMPLETE";
    /**
     * 删除文件
     */
    public static final String ACTION_DELETEDATA = "com.beanpodtech.allinone.service.action.DELETE";


    /**
     * 暂时不用
     */
    public static final String ACTION_TIME_OUT = "com.beanpodtech.allinone.service.action.TIME_OUT";
    public static final String ACTION_FOO = "com.beanpodtech.allinone.service.action.FOO";
    public static final String ACTION_BAZ = "com.beanpodtech.allinone.service.action.BAZ";
    public static final String ACTION_RESTART = "com.beanpodtech.allinone.service.action.RESTART";
    /**
     * 视频Id
     */
    public static final String EXTRA_VIDEOID = "com.beanpodtech.allinone.service.extra.VIDEOID";
    /**
     * 课程Id
     */
    public static final String EXTRA_COURSEID = "com.beanpodtech.allinone.service.extra.COURSEID";
    /**
     * 当前播放时间
     */
    public static final String EXTRA_PLAYINGTIME = "com.beanpodtech.allinone.service.extra.PLAYINGTIME";
    /**
     * 需要传递的bitmap
     */
    public static final String EXTRA_BITMAP = "com.beanpodtech.allinone.service.extra.BITMAP";
    /**
     *
     */
    public static final String EXTRA_ISNEEDTIMING = "com.beanpodtech.allinone.service.extra.ISNEEDTIMING";

    public TimeCounterService() {
        super("TimeCounterService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        timeCounter = TimeCounter.getInstance(EduApplication.getContext());
        if (intent != null) {
            final String action = intent.getAction();
            final String videoId = intent.getStringExtra(EXTRA_VIDEOID);
            final String courseId = intent.getStringExtra(EXTRA_COURSEID);
            if (TextUtils.isEmpty(videoId) && TextUtils.isEmpty(courseId)) return;
            final int playingTime = intent.getIntExtra(EXTRA_PLAYINGTIME, DEFAULT_PLAYINGTIME);
            final byte[] bitmap = timeCounter.getVideoSecondBitMap();
            final boolean isNeedTiming = intent.getBooleanExtra(EXTRA_ISNEEDTIMING, true);
            if (ACTION_START.equals(action)) {
                handleActionStart(videoId, courseId, playingTime, bitmap);
            } else if (ACTION_TIME_UP.equals(action)) {
                handleActionTimeUp(videoId, courseId, playingTime, bitmap, isNeedTiming);
            } else if (ACTION_PAUSE.equals(action)) {
                //handleActionPause(videoId, courseId, playingTime, bitmap, isNeedTiming);
            } else if (ACTION_CLOSED.equals(action)) {
                handleActionClosed(videoId, courseId, playingTime, bitmap, isNeedTiming);
            } else if (ACTION_COMPLETE.equals(action)) {
                handleActionComplete(videoId, courseId, playingTime, bitmap, isNeedTiming);
            } else if (ACTION_DELETEDATA.equals(action)) {
                handleActionDelete();
                /* else if (ACTION_RESTART.equals(action)) {
                handleActionRestart(param1, param2);
            } else if (ACTION_TIME_OUT.equals(action)) {
                handleActionTimeOut(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                handleActionBaz(param1, param2);
            }*/
            }
        }
    }


    /**
     * 视频准备开始播放时
     *
     * @param videoId     视频Id
     * @param courseId    课程Id
     * @param playingTime 播放的时长  60一次
     * @param bitmap      计算计时的位
     */
    private void handleActionStart(String videoId, String courseId, int playingTime, byte[] bitmap) {

        SyncUtils.getInstance().requestBody(HttpUtils.getRequestJson(getTimeCounterDataRequestBody(videoId))).callback(new OnSyncServerCallBack() {
            @Override
            public void onSyncServer(Object object) {
                if (object instanceof BuyVideoIdBean) {
                    BuyVideoIdBean buyVideoIdBean = (BuyVideoIdBean) object;
                    if (buyVideoIdBean != null) {
                        if (buyVideoIdBean.getStatus() == -1) {
                            // TODO: 2020/7/3 禁止使用状态需要处理
                            return;
                        }
                        if (buyVideoIdBean.getReverseData() != null) {
                            timeCounter.setServerBitmapExsitFlag(true);
                            byte[] decoded = Base64.decode(buyVideoIdBean.getReverseData(), Base64.DEFAULT);
                            byte[] videoSecondBitMap = null;
                            if (timeCounter.isNativeBitmapExsitFlag()) {
                                videoSecondBitMap = timeCounter.getVideoSecondBitMap();
                                // TODO: 2020/7/3  需要加判断两个数组长度是否一样
                                if (videoSecondBitMap != null) {
                                    byte[] bitmapResult = CounterNative.bitmapOROperation(videoSecondBitMap, decoded, decoded.length);
                                    if (bitmapResult != null) {
                                        timeCounter.setVideoSecondBitMap(bitmapResult);
                                        timeCounter.setBitmapExsitFlag(true);
                                    } else {
                                        timeCounter.setVideoSecondBitMap(decoded);
                                        timeCounter.setBitmapExsitFlag(true);
                                    }
                                } else {
                                    timeCounter.setVideoSecondBitMap(decoded);
                                    timeCounter.setBitmapExsitFlag(true);
//                            timeCounter.set
                                }
                            } else {
                                // TODO: 2020/7/3  此处增加线程休眠 和状态
                                while (!timeCounter.isNativeBitmapExsitFlag()) {
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                timeCounter.setVideoSecondBitMap(decoded);
                                timeCounter.setBitmapExsitFlag(true);
                            }
                        } else {
                            timeCounter.setServerBitmapExsitFlag(false);
                        }
                    }
                    timeCounter.setServerBitmapCheckState(Contants.BITMAP_CHECK_STATE);
                }
            }
        }).build(SyncUtils.BUYVIDEOID);


    }

    /**
     * 到60S该传值
     *
     * @param videoId     视频Id
     * @param courseId    课程Id
     * @param playingTime 播放的时长  60一次
     * @param bitmap      计算计时的位
     */
    private void handleActionTimeUp(String videoId, String courseId, int playingTime, byte[] bitmap, boolean isNeedTiming) {
        if (isNeedTiming) {
            sendPlayingTime(videoId, courseId, playingTime);
            sendPlayingBitmap(videoId);
        }
    }


    /**
     * 视频暂停
     *
     * @param videoId     视频Id
     * @param courseId    课程Id
     * @param playingTime 播放的时长  60一次
     * @param bitmap      计算计时的位
     */
    private void handleActionPause(String videoId, String courseId, int playingTime, byte[] bitmap, boolean isNeedTiming) {
        if (playingTime >= Contants.TIME_UPLOAD_INTERVAL_FOR_STOP) {
            if (isNeedTiming) {
                sendPlayingTime(videoId, courseId, playingTime);
                sendPlayingBitmap(videoId);
            }
        }
    }

    /**
     * 页面关闭
     *
     * @param videoId     视频Id
     * @param courseId    课程Id
     * @param playingTime 播放的时长  60一次
     * @param bitmap      计算计时的位
     */
    private void handleActionClosed(String videoId, String courseId, int playingTime, byte[] bitmap, boolean isNeedTiming) {
        if (playingTime >= Contants.TIME_UPLOAD_INTERVAL_FOR_STOP) {
            if (isNeedTiming) {
                sendPlayingTime(videoId, courseId, playingTime);
                sendPlayingBitmap(videoId);
            }
        }
    }

    /**
     * 播放完成
     *
     * @param videoId     视频Id
     * @param courseId    课程Id
     * @param playingTime 播放的时长  60一次
     * @param bitmap      计算计时的位
     */
    private void handleActionComplete(String videoId, String courseId, int playingTime, byte[] bitmap, boolean isNeedTiming) {
        if (playingTime >= Contants.TIME_UPLOAD_INTERVAL_FOR_STOP) {
            if (isNeedTiming) {
                sendPlayingTime(videoId, courseId, playingTime);
                sendPlayingBitmap(videoId);
            }
        }
    }

    /**
     * 删除文件
     */
    private void handleActionDelete() {

    }

    /**
     * 同步播放60S时长
     *
     * @param videoId     视频id
     * @param courseId    课程Id
     * @param playingTime 时长 <=60S   毫秒
     */
    private void sendPlayingTime(String videoId, String courseId, int playingTime) {
        SyncUtils.getInstance().requestBody(HttpUtils.getRequestJson(getSendPlayingTimeRequestBody(videoId, courseId, playingTime))).callback(new OnSyncServerCallBack() {
            @Override
            public void onSyncServer(Object object) {
                if (object != null && object instanceof AnycPlayingTimeBean) {
                    AnycPlayingTimeBean bean = (AnycPlayingTimeBean) object;
                    if (bean.getStatus() == -1) {
                        Intent intent = new Intent();
                        intent.setAction(Contants.ACTION_SENDLEFT);
                        intent.putExtra(Contants.LEFT_TIME, -1);
                        sendBroadcast(intent);
                    }
                    String leftTime = bean.getLeftTime();
//                    bean.getUserTime();

                    BigDecimal bigDecimal = new BigDecimal(leftTime);
//                    Log.i(TAG, "======left=" + leftTime + " intValue=" + bigDecimal.intValue());

                    if (bigDecimal.intValue() <= 300) {
                        // TODO: 2020/7/3 增加判断剩余时长逻辑  发送广播
                        Intent intent = new Intent();
                        intent.setAction(Contants.ACTION_SENDLEFT);
                        intent.putExtra(Contants.LEFT_TIME, bigDecimal.intValue());
                        sendBroadcast(intent);
                    }
                }
            }
        }).build(SyncUtils.SENDPLAYINGTIME);
    }

    /**
     * 同步播放位翻转的bitmap
     *
     * @param videoId 视频Id
     */
    private void sendPlayingBitmap(String videoId) {
        byte[] videoSecondBitMap = timeCounter.getVideoSecondBitMap();
        if (videoSecondBitMap != null) {

        }
        String encodeToString = Base64.encodeToString(videoSecondBitMap, Base64.DEFAULT);
//        String encodeToString = Base64.getEncoder().encodeToString(videoSecondBitMap);
        SyncUtils.getInstance().requestBody(HttpUtils.getRequestJson(getSendPlayingBitmapRequestBody(encodeToString, videoId))).callback(new OnSyncServerCallBack() {
            @Override
            public void onSyncServer(Object object) {
                if (object != null && object instanceof BaseRequestBean) {
                    int status = ((BaseRequestBean) object).getStatus();
                    if (status == -1) {
                        Intent intent = new Intent();
                        intent.setAction(Contants.ACTION_SENDLEFT);
                        intent.putExtra(Contants.LEFT_TIME, -1);
                        sendBroadcast(intent);
                        // TODO: 2020/7/3 出现登录异常情况
                    } else if (status == 0) {
                        Log.i(TAG, "insert success");
                    } else {
                        Log.i(TAG, "insert fail");
                    }
                }
            }
        }).build(SyncUtils.ADDORUPDATE);
    }

    /**
     * @param encodeToString base64之后的byte[]
     * @return
     */
    private HashMap<String, String> getSendPlayingBitmapRequestBody(String encodeToString, String videoId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("reverseData", encodeToString);
        return map;
    }

    private HashMap<String, String> getSendPlayingTimeRequestBody(String videoId, String courseId, int time) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("classId", courseId);
        map.put("playingTime", time + "");
        return map;
    }

    private HashMap<String, String> getTimeCounterDataRequestBody(String videoId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        return map;
    }

    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
//        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
//        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void handleActionTimeOut(String param1, String param2) {
        // TODO: Handle action Foo
//        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void handleActionRestart(String param1, String param2) {
        // TODO: Handle action Foo
//        throw new UnsupportedOperationException("Not yet implemented");
    }
}