package com.sunzee.ui.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import com.hboxs.serialport.SerialPortDevice;
import com.hboxs.serialport.SerialPortManager;
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.adapter.GeneralParameterAdapter;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.mvp.generalparameter.GeneralParameterPresenter;
import com.sunzee.mvp.generalparameter.GeneralParameterView;
import com.sunzee.thread.generalparameter.ThreadPoolGeneralParameter;
import com.sunzee.utils.HexadecimalUtil;
import com.sunzee.utils.PreventSpeedClickUtil;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 通用参数界面 fragment
 */
public class GeneralParameterFragment extends MvpFragment<GeneralParameterPresenter> implements GeneralParameterView {
    private final int[] paraName = {R.string.all_clean};
    private final String[] paraAddress = {"M17"};
    private RecyclerView mRvCrrency;
    private GeneralParameterAdapter mGeneralParameterAdapter;
    private ThreadPoolGeneralParameter mPoolGeneralParameter = new ThreadPoolGeneralParameter();
    private PreventSpeedClickUtil mPreventSpeedClickUtil;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_general_parameter, container, false);
        initView(inflate);
        initEvent();
        return inflate;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        showLoading();
        mPoolGeneralParameter.stopAll();
        mPoolGeneralParameter.startALLRead();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        mPoolGeneralParameter.stopAll();
        Log.d(TAG, "onDestroyView: ");
        super.onDestroyView();
    }

    private void initEvent() {
        mGeneralParameterAdapter.setItemListener(new GeneralParameterAdapter.ItemParaClickListener() {
            @Override
            public void onItemListener(View view, int position, String text) {
                //防止快速点击
                if (!mPreventSpeedClickUtil.isFastClick()) {
                    return;
                }
                //点击的时候就开始写入
                final String address = paraAddress[position];
                CheckBox checkBox = (CheckBox) view;
                if (!checkBox.isChecked()) {
                    //为什么每次开启之前都需要关掉呢？因为有可能收不到数据，没有停止，那么我们有必要开启之前就关掉。
                    mPoolGeneralParameter.stopRst();
                    mPoolGeneralParameter.startRst(address);
                } else {
                    //为什么每次开启之前都需要关掉呢？因为有可能收不到数据，没有停止，那么我们有必要开启之前就关掉。
                    mPoolGeneralParameter.stopRst();
                    mPoolGeneralParameter.startSet(address);
                }
                showLoading();
            }
        });
    }

    private void initView(View inflate) {
        mRvCrrency = inflate.findViewById(R.id.rv_currency);
        mGeneralParameterAdapter = new GeneralParameterAdapter(paraName);
        GridLayoutManager layoutManager = new GridLayoutManager(BaseApplication.getContext(), 9, GridLayoutManager.HORIZONTAL, false);
        mRvCrrency.setAdapter(mGeneralParameterAdapter);
        mRvCrrency.setLayoutManager(layoutManager);
        mPreventSpeedClickUtil = new PreventSpeedClickUtil();
    }

    @Override
    protected GeneralParameterPresenter createPresenter() {
        return new GeneralParameterPresenter(this);
    }

    private static final String TAG = "GeneralParameterFragmen";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                break;
            case sendError:
                break;
            case ack:
                //写入数据成功的反馈
                mPoolGeneralParameter.stopRst();
                mPoolGeneralParameter.stopSet();
                hideLoading();
                break;
            case nak:
                break;
            case disconnected:
                SerialPortDevice device = new SerialPortDevice("/dev/ttyS2", "9600");
                SerialPortManager.getInstance().open(device);
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                String name = messageEvent.getName();
                if ("M600".equals(name)) {
                    return;
                }
                String result1 = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                //通过校验
                if (name.equals("M17")) {
//                    ArrayList<String> results = HexadecimalUtil.flipString(result1);
//                    long data = HexadecimalUtil.hex2dec(results1.get(0));
                    String s = HexadecimalUtil.hexStringToByte(result1);
                    String s1 = HexadecimalUtil.flipString(s, 8);
                    List<String> lis = Arrays.asList(s1.split(""));
                    ArrayList<String> list = new ArrayList(lis);
                    list.remove(0);
                    String data = list.get(1);
                    Log.d(TAG, "M17event: " + list);
                    if (!"0".equals(data)) {
                        setStatus(0, data);
                    }
                    mPoolGeneralParameter.stopReadM17();
                }
                hideLoading();
                break;
        }

    }

    private void setStatus(int position, String data) {
        View view = mRvCrrency.getChildAt(position);
        if (null != mRvCrrency.getChildViewHolder(view)) {
            GeneralParameterAdapter.ViewHolder viewHolder = (GeneralParameterAdapter.ViewHolder) mRvCrrency.getChildViewHolder(view);
            if (!"0".equals(data)) {
                //当它为选择状态时，无需设置，避免闪硕
                if (!viewHolder.cbManual.isChecked()) {
                    viewHolder.cbManual.setChecked(true);
                }
            } else {
                if (viewHolder.cbManual.isChecked()) {
                    viewHolder.cbManual.setChecked(false);
                }

            }
        }
    }

    @Override
    public void showLoading() {
        showProgressDialog();
    }

    @Override
    public void hideLoading() {
        dismissProgressDialog();
    }

    public ProgressDialog progressDialog;

    public ProgressDialog showProgressDialog() {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中");
        progressDialog.show();
        return progressDialog;
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            progressDialog.dismiss();
        }
    }
}
