package com.sunzee.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.AsciiUtils;
import com.sunzee.R;
import com.sunzee.base.MvpActivity;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.domain.ParameterBean;
import com.sunzee.model.message.ApiMessageEvent;
import com.sunzee.model.message.DownLoadMessageEvent;
import com.sunzee.mvp.advertising.AdvertisingPresenter;
import com.sunzee.mvp.advertising.AdvertisingView;
import com.sunzee.thread.advanceparameter.ThreadPoolAdvanceParameter;
import com.sunzee.ui.dialog.WarringDialog;
import com.sunzee.utils.AlarmManagerUtil;
import com.sunzee.utils.GeTuiUtil;
import com.sunzee.utils.HexadecimalUtil;
import com.sunzee.utils.LongClickUtils;
import com.sunzee.utils.SimplePlayerUtils;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;
import com.wuxiaolong.androidutils.library.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 广告界面 activity
 */
public class AdvertisingActivity extends MvpActivity<AdvertisingPresenter> implements AdvertisingView {


    private static final String TAG = "AdvertisingActivity";
    private SurfaceView mAdSurfaceView;
    private SurfaceView mAdbSurfaceView;
    private SimplePlayerUtils mRightsimplePlayer;
    private SimplePlayerUtils mLeftsimplePlayer;
    private ImageView mAdImageview;
    private ImageView mAdbImageview;
    private GeTuiUtil mGeTuiUtil;
    private RelativeLayout mRlRoot;
    private TextView mTvTime;
    private MyHandler myHandler;
    private TextView mTvEquipmentNo;
    private ThreadPoolAdvanceParameter mPoolAdvanceParameter = new ThreadPoolAdvanceParameter();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertising);
        EventBus.getDefault().register(this);
        mGeTuiUtil = new GeTuiUtil(this);
        mGeTuiUtil.geTui();
        initView();
        initEvent();
        AlarmManagerUtil.setAlarm(this, 1, 12, 16, 0, 6, 0, "闹钟响了32");
    }

    private void initEvent() {
        LongClickUtils.setLongClick(new Handler(), mRlRoot, 10, new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(AdvertisingActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                return false;
            }
        });
    }

    private void initView() {
        myHandler = new MyHandler(this);
        mAdSurfaceView = findViewById(R.id.sf_cor_ad);
        mAdImageview = findViewById(R.id.iv_cor_ad);
        mAdbSurfaceView = findViewById(R.id.sf_cor_adb);
        mAdbImageview = findViewById(R.id.iv_cor_adb);
        mRlRoot = findViewById(R.id.rl_root);
        mTvTime = findViewById(R.id.tv_time1);
        mTvEquipmentNo = findViewById(R.id.tv_equipment_no1);
        Log.d(TAG, "initView: " + Heartbeat.deviceId);
        if (Heartbeat.deviceId != null && Heartbeat.deviceId.length() > 7) {
            mTvEquipmentNo.setText(Heartbeat.deviceId != null ? Heartbeat.deviceId.substring(Heartbeat.deviceId.length() - 6) : "");

        }
        //1.初始化播放器
        mRightsimplePlayer = new SimplePlayerUtils(mAdSurfaceView);
        mRightsimplePlayer.setImageView(mAdImageview);
        mLeftsimplePlayer = new SimplePlayerUtils(mAdbSurfaceView);
        mLeftsimplePlayer.CloseVolume();
        mLeftsimplePlayer.setImageView(mAdbImageview);
        LogUtil.d(TAG, "setup: " + mRightsimplePlayer);
        LogUtil.d(TAG, "setup: " + mLeftsimplePlayer);
        play();
        startRefreshime();
        mPoolAdvanceParameter.startALLRead();
    }

    private void play() {
        mvpPresenter.play();
    }


    /**
     * 播放左边视频
     *
     * @param playFileList
     */
    @Override
    public void playLeft(ArrayList<File> playFileList) {
        mLeftsimplePlayer.setFileData(playFileList);
        mLeftsimplePlayer.playVideo();
    }

    /**
     * 播放右边视频
     *
     * @param playFile
     */
    @Override
    public void playRight(ArrayList<File> playFile) {
        mRightsimplePlayer.setFileData(playFile);
        mRightsimplePlayer.playVideo();
    }

    @Override
    public void updateTime(CharSequence sysTimeStr) {
        mTvTime.setText(sysTimeStr);
    }

    @Override
    public void getDataSuccess() {
        String[] values = mPoolAdvanceParameter.getValues();
        ArrayList<ParameterBean> parameterBeans = new ArrayList<>();
       String[] paraAddress = {
                "D426", "D427", "D428", "D429",
                "D430", "D431"};
        for (int i = 0; i < values.length; i++) {
            parameterBeans.add(new ParameterBean(paraAddress[i], values[i]));
        }
        mvpPresenter.updateAdvanced(parameterBeans);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLeftsimplePlayer.onDestroy();
        mRightsimplePlayer.onDestroy();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        myHandler.removeCallbacksAndMessages(null);
        myHandler = null;
        stopRefreshTime();
    }

    private long mPressTime = 0L;

    /**
     * 两次点击才能退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mPressTime < 1000) {
                finish();
            } else {
                ToastUtil.showToast("再按一次退出");
                mPressTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //个推相关
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(DownLoadMessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case downloadAll:
                play();
                break;
            default:
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(ApiMessageEvent messageEvent) {
        switch (messageEvent.getName()) {
            case "pushTimeRule":
                //推送最新规则
                LogUtil.d(TAG, "pushTimeRule:");
                LogUtil.e(TAG, "event: 接收到规则");
                play();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
            case sendError:
            case ack:
                break;
            case nak:
                break;
            case disconnected:
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                String name = messageEvent.getName();
                if ("M600".equals(name)) {
                    return;
                }
                if (responseFrame.isValidSum()) {
                    //通过校验
                    Log.d(TAG, "event: " + name);
                    String result = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                    ArrayList<String> results = HexadecimalUtil.flipString(result);
                    mvpPresenter.setAdvanced(name, results, mPoolAdvanceParameter);
                }
                break;
        }
    }

    @Override
    protected AdvertisingPresenter createPresenter() {
        AdvertisingPresenter advertisingPresenter = new AdvertisingPresenter(this);
        advertisingPresenter.requstCleanRule();
        advertisingPresenter.requestCleanTimeAndRemaining();
        return advertisingPresenter;
    }

    /**
     * 主要用于更新系统时间
     */
    public static class MyHandler extends Handler {
        //持有弱引用HandlerActivity,GC回收时会被回收掉.
        private final WeakReference<AdvertisingActivity> mActivty;

        public MyHandler(AdvertisingActivity activity) {
            mActivty = new WeakReference<AdvertisingActivity>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            AdvertisingActivity activity = mActivty.get();
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime);//时间显示格式
                    activity.mTvTime.setText(sysTimeStr);
                    break;
            }
        }
    }

    private Timer timerGetTime;
    private TimerTask timerGetTimerTak;

    //时间日期的更新
    private void startRefreshime() {
        timerGetTime = new Timer();
        timerGetTimerTak = new TimerTask() {
            @Override
            public void run() {
                myHandler.sendEmptyMessage(1);
            }
        };
        timerGetTime.schedule(timerGetTimerTak, 0, 1000);
    }

    private void stopRefreshTime() {
        if (timerGetTime != null) {
            timerGetTime.cancel();
            timerGetTime = null;
        }
        if (timerGetTimerTak != null) {
            timerGetTimerTak.cancel();
            timerGetTimerTak = null;
        }
    }
}
