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.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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 通用参数界面 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();

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


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

    private void initEvent() {
        mGeneralParameterAdapter.setItemListener(new GeneralParameterAdapter.ItemParaClickListener() {
            @Override
            public void onItemListener(View view, int position, String text) {
                //点击的时候就开始写入
                final String address = paraAddress[position];
                CheckBox checkBox = (CheckBox) view;
                if (!checkBox.isChecked()) {
                    mPoolGeneralParameter.startRst(address);
                } else {
                    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);
    }

    @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 result1 = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                //通过校验
                String name = messageEvent.getName();
                if (name.equals("M17")) {
                    ArrayList<String> results1 = HexadecimalUtil.flipString(result1);
                    long data = HexadecimalUtil.hex2dec(results1.get(0));
                    if (data != 0) {
                        setStatus(0, data);
                    }
                    mPoolGeneralParameter.stopReadM17();
                }
                hideLoading();
                break;
        }

    }

    private void setStatus(int position, long data) {
        View view = mRvCrrency.getChildAt(position);
        if (null != mRvCrrency.getChildViewHolder(view)) {
            GeneralParameterAdapter.ViewHolder viewHolder = (GeneralParameterAdapter.ViewHolder) mRvCrrency.getChildViewHolder(view);
            if (data != 0) {
                //当它为选择状态时，无需设置，避免闪硕
                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();
        }
    }
}
