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.DebugParameterAdapter;
import com.sunzee.adapter.GeneralParameterAdapter;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.mvp.debug.DebugPresenter;
import com.sunzee.mvp.debug.DebugView;
import com.sunzee.thread.debugparameter.ThreadPoolDebugParameter;
import com.sunzee.utils.HexadecimalUtil;

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 DebugFragment extends MvpFragment<DebugPresenter> implements DebugView {
    private final int[] paraName = {
            R.string.debug_1, R.string.debug_2,
            R.string.debug_3, R.string.debug_4,
            R.string.debug_5, R.string.debug_6,
            R.string.debug_7
    };
    private final String[] paraAddress = {
            "M311", "M312", "M313", "M315",
            "M316", "M317", "M318"};
    private RecyclerView mRvDebugList;
    private DebugParameterAdapter mDebugParameterAdapter;
    private ThreadPoolDebugParameter mPoolDebugParameter = new ThreadPoolDebugParameter();


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

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

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private static final String TAG = "DebugFragment";

    private void initEvent() {
        mDebugParameterAdapter.setItemListener(new DebugParameterAdapter.ItemParaClickListener() {
            @Override
            public void onItemListener(View view, int position, String text) {
                //点击的时候就开始写入
                final String address = paraAddress[position];
                CheckBox checkBox = (CheckBox) view;
                if (!checkBox.isChecked()) {
                    mPoolDebugParameter.startRst(address);
                } else {
                    mPoolDebugParameter.startSet(address);
                }
                showLoading();
            }
        });
    }

    private void initView(View inflate) {
        mRvDebugList = inflate.findViewById(R.id.rv_degbuglist);
        mDebugParameterAdapter = new DebugParameterAdapter(paraName);
        GridLayoutManager layoutManager = new GridLayoutManager(BaseApplication.getContext(), 9, GridLayoutManager.HORIZONTAL, false);
        mRvDebugList.setAdapter(mDebugParameterAdapter);
        mRvDebugList.setLayoutManager(layoutManager);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                break;
            case sendError:
                break;
            case ack:
                mPoolDebugParameter.stopRst();
                mPoolDebugParameter.stopSet();
                Log.d(TAG, "event: 写入成功");
                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();
                if (responseFrame.isValidSum()) {
                    //通过校验
                    String name = messageEvent.getName();
                    Log.d(TAG, "event: " + name);
                    String result = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                    ArrayList<String> results = HexadecimalUtil.flipString(result);
                    //    转成2进制
                    String s = HexadecimalUtil.hexStringToByte(result);
                    //翻转后的数据
                    String s1 = HexadecimalUtil.flipString(s, 8);
                    List<String> lis = Arrays.asList(s1.split(""));
                    ArrayList<String> list = new ArrayList(lis);
                    list.remove(0);
                    mvpPresenter.setDebugParameter(name, list, mPoolDebugParameter);
                    break;
                }
        }
    }

    @Override
    public void getDataSuccess() {
        getValue(mPoolDebugParameter.getValues());
    }

    /**
     * 改变对应的状态
     *
     * @param value
     */
    private void getValue(ArrayList<String> value) {
        //311-318
        for (int i = 0; i < value.size(); i++) {
            View view = mRvDebugList.getChildAt(i);
            if (null != mRvDebugList.getChildViewHolder(view)) {
                DebugParameterAdapter.ViewHolder viewHolder = (DebugParameterAdapter.ViewHolder) mRvDebugList.getChildViewHolder(view);
                if (!value.get(i).equals("0")) {
                    //当它为选择状态时，无需设置，避免闪硕
                    if (!viewHolder.cbManual.isChecked()) {
                        viewHolder.cbManual.setChecked(true);
                    }
                } else {
                    if (viewHolder.cbManual.isChecked()) {
                        viewHolder.cbManual.setChecked(false);
                    }
                }
            }
        }

    }

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

    @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();
        }
    }
}
