package aicare.net.cn.sdk.ailinksdkdemoandroid;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.pingwang.bluetoothlib.AILinkBleManager;
import com.pingwang.bluetoothlib.bean.SupportUnitBean;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;
import com.pingwang.bluetoothlib.utils.BleStrUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.SP;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;
import cn.net.aicare.modulelibrary.module.Transmission.TransmissionDeviceData;

/**
 * 透传界面
 */
public class TransmissionActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, TransmissionDeviceData.MyBleCallback {

    private final String TRANSMISSION_DATA_KEY = "TRANSMISSION_DATA_KEY";
    private TextView tv_device_info;
    private EditText et, et_cid, et_a6, et_customize, etReceive, etSend;
    private Button send, send_a6, bt_clear, bt_clear_log, btnSetAutoSend, send_customize;
    private Button btDis, btConnect;
    private ListView mListView;
    private List<String> mlogList;
    private final int ToRefreUi = 1;
    private MHandler mMHandler;
    private ArrayAdapter listAdapter;
    private String mAddress;
    private TransmissionDeviceData mTransmissionDeviceData;
    private boolean isPause = false;
    private Gson mGson = new Gson();
    private SaveDataBean mSaveDataBean;

    @Override
    public void onServiceSuccess() {
        mlogList.add(0, "服务与界面建立连接成功");
        mMHandler.sendEmptyMessage(ToRefreUi);
//        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                if (tv_device_info != null) {
                    tv_device_info.setText("MAC:" + bleDevice.getMac());
                }
                mTransmissionDeviceData = new TransmissionDeviceData(bleDevice);
                mTransmissionDeviceData.setMyBleCallback(this);


            }
        }
    }

    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.removeOnCallbackBle(this);
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //禁止横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_transmission);
        WeakReference weakReference = new WeakReference(new MHandler());
        mMHandler = (MHandler) weakReference.get();
        tv_device_info = findViewById(R.id.tv_device_info);
        et = findViewById(R.id.et);
        et_a6 = findViewById(R.id.et_a6);
        et_cid = findViewById(R.id.et_cid);
        btnSetAutoSend = findViewById(R.id.btnSetAutoSend);
        send = findViewById(R.id.send);
        send_a6 = findViewById(R.id.send_a6);
        et_customize = findViewById(R.id.et_customize);
        send_customize = findViewById(R.id.send_customize);
        etReceive = findViewById(R.id.etReceive);
        etSend = findViewById(R.id.etSend);
        bt_clear = findViewById(R.id.bt_clear);
        bt_clear_log = findViewById(R.id.bt_clear_log);
        mListView = findViewById(R.id.listview);
        btDis = findViewById(R.id.btDis);
        btConnect = findViewById(R.id.btConnect);
        send.setOnClickListener(this);
        send_a6.setOnClickListener(this);
        send_customize.setOnClickListener(this);
        findViewById(R.id.btPause).setOnClickListener(this);
        bt_clear.setOnClickListener(this);
        bt_clear_log.setOnClickListener(this);
        btDis.setOnClickListener(this);
        btConnect.setOnClickListener(this);
        btnSetAutoSend.setOnClickListener(this);
        mAddress = getIntent().getStringExtra("mac");
        mlogList = new ArrayList<>();
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mlogList);
        mListView.setAdapter(listAdapter);
        mGson = new Gson();
        String json = (String) SP.getInstance().get(TRANSMISSION_DATA_KEY, "");
        if (!TextUtils.isEmpty(json)) {
            mSaveDataBean = mGson.fromJson(json, SaveDataBean.class);
            et_cid.setText(mSaveDataBean.cid);
            et.setText(mSaveDataBean.a7Data);
            et_a6.setText(mSaveDataBean.a6Data);
            et_customize.setText(mSaveDataBean.customizeData);
        }


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.send) {
            if (!et.getText().toString().isEmpty() && !et_cid.getText().toString().isEmpty()) {
                String hex = et.getText().toString().toUpperCase().trim();
                byte[] hexStr = BleStrUtils.stringToByte(hex);
                String cid = et_cid.getText().toString().toUpperCase().trim();
                int hexStrCid = Integer.parseInt(cid, 16);
                if (mTransmissionDeviceData != null) {
                    mTransmissionDeviceData.setSendData(hexStrCid, hexStr);
                }
            }
        } else if (id == R.id.bt_clear) {
            et.setText("");
            et_a6.setText("");
            et_customize.setText("");
        } else if (id == R.id.bt_clear_log) {
            mlogList.clear();
            mMHandler.sendEmptyMessage(ToRefreUi);
        } else if (id == R.id.send_a6) {
            String hex = et_a6.getText().toString().toUpperCase().trim();
            if (!TextUtils.isEmpty(hex)) {
                byte[] hexStr = BleStrUtils.stringToByte(hex);
                if (mTransmissionDeviceData != null) {
                    mTransmissionDeviceData.setSendDataA6(hexStr);
                }
            }
        } else if (id == R.id.send_customize) {
            String hex = et_customize.getText().toString().toUpperCase().trim();
            if (!TextUtils.isEmpty(hex)) {
                byte[] hexStr = BleStrUtils.stringToByte(hex);
                if (mTransmissionDeviceData != null) {
                    mTransmissionDeviceData.setSendDataCustomize(hexStr);
                }
            }
        } else if (id == R.id.btnSetAutoSend) {
            mReceiveStr = etReceive.getText().toString().trim();
            mSendStr = etSend.getText().toString().trim();
            addLog("设置成功:发送的数据通过A7通道发送");
        } else if (id == R.id.btPause) {
            isPause = !isPause;
        } else if (id == R.id.btDis) {
            AILinkBleManager.getInstance().disconnectAll();
        } else if (id == R.id.btConnect) {
            AILinkBleManager.getInstance().connectDevice(mAddress);
        }
    }

    private String mReceiveStr = "";
    private String mSendStr = "";

    /**
     * 检查数据自动发送
     *
     * @param data 数据
     */
    public void checkDataAutoSend(String data) {
        data = data.replace(" ","");
        if (TextUtils.isEmpty(mReceiveStr) || TextUtils.isEmpty(mSendStr) || TextUtils.isEmpty(data)) {
            return;
        }
        if (data.startsWith(mReceiveStr)) {
            byte[] hexStr = BleStrUtils.stringToByte(mSendStr);
            String cid = et_cid.getText().toString().toUpperCase().trim();
            int hexStrCid = Integer.parseInt(cid, 16);
            if (mTransmissionDeviceData != null) {
                mTransmissionDeviceData.setSendData(hexStrCid, hexStr);
            }
        }
    }


    @Override
    public void onVersion(String version) {

    }

    @Override
    public void showData(String data, int type) {
        addLog("收A7 payload数据" + TimeUtils.getTimeSSS() + "cid=" + type + "\n" + data);
        checkDataAutoSend(data);
    }

    @Override
    public void onSupportUnit(List<SupportUnitBean> list) {

    }

    @Override
    public void onCid(int cid, int vid, int pid) {
        addLog("收" + TimeUtils.getTime() + "cid:" + cid + "||vid:" + vid + "||pid:" + pid);
    }

    @Override
    public void otherData(byte[] hex, String data) {
        addLog("收 透传数据" + TimeUtils.getTime() + data);
        checkDataAutoSend(data);
    }

    @Override
    public void a6Data(byte[] hex, String data) {
        addLog("收A6 payload数据" + TimeUtils.getTime() + data);
        checkDataAutoSend(data);
    }

    @Override
    public void sendData(String data) {
        addLog("发 " + TimeUtils.getTimeSSS() + data);
    }

    @Override
    public void onServicesDiscovered(String mac) {
        onServiceSuccess();
        mlogList.add(0, "连接成功: " + mac);
        mMHandler.sendEmptyMessage(ToRefreUi);
    }

    @Override
    public void onDisConnected(String mac, int code) {
        mlogList.add(0, "连接断开: " + mac + "  code:" + code);
        mMHandler.sendEmptyMessage(ToRefreUi);
    }

    private class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == ToRefreUi) {
                if (listAdapter != null) {
                    listAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAILinkBleManager != null) {
            mAILinkBleManager.disconnectAll();
        }
        if (mSaveDataBean == null) {
            mSaveDataBean = new SaveDataBean();
        }
        mSaveDataBean.cid = et_cid.getText().toString().trim();
        mSaveDataBean.a7Data = et.getText().toString().trim();
        mSaveDataBean.a6Data = et_a6.getText().toString().trim();
        mSaveDataBean.customizeData = et_customize.getText().toString().trim();
        String json = mGson.toJson(mSaveDataBean);
        SP.getInstance().put(TRANSMISSION_DATA_KEY, json);
    }


    private void addLog(String log) {
        if (isPause) {
            return;
        }
        mlogList.add(0, log);
        mMHandler.sendEmptyMessage(ToRefreUi);
    }


    class SaveDataBean {
        String cid = "";
        String a7Data = "";
        String a6Data = "";
        String customizeData = "";
    }

}
