package com.sunzee.ui.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
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.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.hboxs.serialport.SerialPortDevice;
import com.hboxs.serialport.SerialPortManager;
import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.frame.WriteCommandFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.AsciiUtils;
import com.hboxs.serialport.util.ByteUtils;
import com.hboxs.serialport.util.HexUtils;
import com.sunzee.R;
import com.sunzee.adapter.AdvanceParameterAdapter;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.mvp.advanceparameter.AdvanceParameterPresenter;
import com.sunzee.mvp.advanceparameter.AdvanceParameterView;
import com.sunzee.thread.advanceparameter.ThreadPoolAdvanceParameter;
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 AdvanceParameterFragment extends MvpFragment<AdvanceParameterPresenter> implements AdvanceParameterView {

    private final int[] paraName = {
            R.string.advance_parameter_7, R.string.advance_parameter_8,
            R.string.advance_parameter_9, R.string.advance_parameter_10,
            R.string.advance_parameter_11, R.string.advance_parameter_12,
    };
    private final String[] paraAddress = {
            "D426", "D427", "D428", "D429",
            "D430", "D431"};
    private RecyclerView mRvCrrency;
    private AdvanceParameterAdapter mAdvanceParameterAdapter;
    private static final String TAG = "AdvanceParameterFragmen";
    private ThreadPoolAdvanceParameter mPoolAdvanceParameter = new ThreadPoolAdvanceParameter(paraAddress);

    @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();
        Log.d(TAG, "onStart: ");
        EventBus.getDefault().register(this);
        showLoading();
        mPoolAdvanceParameter.startALLRead();
    }

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

    private void initEvent() {
        mAdvanceParameterAdapter.setItemListener(new AdvanceParameterAdapter.ItemParaClickListener() {
            @Override
            public void onItemListener(View view, int position, String text) {
                View v = mRvCrrency.getChildAt(position);
                if (null != mRvCrrency.getChildViewHolder(v)) {
                    String data = ByteUtils.decimal2fitHex(Integer.valueOf(text));
                    mPoolAdvanceParameter.startWrite(paraAddress[position], HexUtils.hexStr2BinStr(data));
                    Log.d(TAG, "onItemListener: "+HexUtils.hexStr2BinStr(data));

                }
                Log.d(TAG, "onItemListener: " + mAdvanceParameterAdapter.getParameterBeans());
            }
        });
        mRvCrrency.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.d(TAG, "onClick: ");
                //隐藏键盘
                @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager)
                        mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return false;
            }
        });
    }

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

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

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

    //--------------------------------------------------loading end------------------
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                break;
            case sendError:
                break;
            case ack:
                Log.d(TAG, "event: 写入成功");
                mPoolAdvanceParameter.stopWrite();
                //todo 上传
                mvpPresenter.updateAdvanced(mAdvanceParameterAdapter.getParameterBeans());
                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);
                    mvpPresenter.setAdvanced(name, results, mPoolAdvanceParameter);
                    hideLoading();
                    break;
                }
        }
    }

    @Override
    public void getDataSuccess() {
        mAdvanceParameterAdapter.setValues(mPoolAdvanceParameter.getValues());
        mAdvanceParameterAdapter.notifyDataSetChanged();
        //todo 上传
        mvpPresenter.updateAdvanced(mAdvanceParameterAdapter.getParameterBeans());
    }


}
