package aicare.net.cn.sdk.ailinksdkdemoandroid;

import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
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.NonNull;
import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.config.BleConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.device.SendDataBean;
import com.pingwang.bluetoothlib.listener.CallbackDisIm;
import com.pingwang.bluetoothlib.listener.OnBleDeviceDataListener;
import com.pingwang.bluetoothlib.listener.OnBleMtuListener;
import com.pingwang.bluetoothlib.listener.OnBleOtherDataListener;
import com.pingwang.bluetoothlib.listener.OnCallbackDis;
import com.pingwang.bluetoothlib.utils.BleDensityUtil;
import com.pingwang.bluetoothlib.utils.BleLog;
import com.pingwang.bluetoothlib.utils.BleStrUtils;
import com.pingwang.bluetoothlib.utils.UuidUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;


/**
 * xing<br>
 * 2019/4/25<br>
 * 测试指令界面
 */
public class TestCmdActivity extends BleBaseActivity implements OnCallbackDis, OnBleDeviceDataListener, View.OnClickListener, OnBleOtherDataListener {

    private TextView tv_receive_number;
    private TextView tv_send_number;

    private static String TAG = TestCmdActivity.class.getName();
    private final int REFRESH_DATA = 3;
    private final int SEND_DATA = 4;
    private List<String> mList;
    private ArrayAdapter listAdapter;
    private Context mContext;
    private EditText et_cmd, et_uuid, et_uuid_server, et_time, et_notify, etIncrementNumber;
    private BleDevice mBleDevice;
    private String mAddress;
    private int sendTime = 1000;
    private UUID sendUuid = null;
    private UUID sendUuidServer = null;
    private String uuidEnd = "-0000-1000-8000-00805F9B34FB";
    private String sendCmd;
    private byte[] sendCmdB;
    private long mSendNumber = 0;
    private long mReceiveNumber = 0;
    private boolean mShowLog = true;
    private boolean mIncrementSend = false;
    private int mNum = 0;
    private int mNumMax = 514;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case REFRESH_DATA:
                    if (listAdapter != null)
                        listAdapter.notifyDataSetChanged();
                    break;

                case SEND_DATA:
                    int intervalTime = sendTime;
                    if (sendUuid != null && sendUuidServer != null && mBleDevice != null) {
                        byte[] sendData = sendCmdB;
                        if (mIncrementSend) {
                            //递增字节发送
                            mNum++;
                            if (mNum > mNumMax) {
                                addLog("递增发送结束");
                                mNum = 1;
                                return;
                            }
                            sendData = new byte[mNum];
                            for (int i = 0; i < mNum; i++) {
                                sendData[i] = (byte) (i);
                            }

                            intervalTime = sendTime + mNum;
                            addLog("发送数据量:" + mNum);
                        }
                        SendDataBean sendDataBean = new SendDataBean(sendData, sendUuid, BleConfig.WRITE_DATA, sendUuidServer);
                        mBleDevice.sendData(sendDataBean);
                        if (intervalTime > 0) {
                            mHandler.sendEmptyMessageDelayed(SEND_DATA, intervalTime);
                        }
                        mSendNumber += sendDataBean.getHex().length;
                        tv_send_number.setText(String.valueOf(mSendNumber));
                    } else {
                        addLog("请先设置特征UUID和服务UUID");
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_cmd);
        mContext = this;
        mAddress = getIntent().getStringExtra("mac");
        init();
    }

    private void init() {
        mList = new ArrayList<>();
        ListView listView = findViewById(R.id.listview);
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        listView.setAdapter(listAdapter);

        findViewById(R.id.clear).setOnClickListener(this);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn_uuid).setOnClickListener(this);
        findViewById(R.id.btn_time).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);
        findViewById(R.id.btn_notify).setOnClickListener(this);
        findViewById(R.id.btn_notify_status).setOnClickListener(this);
        findViewById(R.id.btn_uuid_server).setOnClickListener(this);
        findViewById(R.id.btn_log).setOnClickListener(this);
        findViewById(R.id.btnIncrementSend).setOnClickListener(this);
        findViewById(R.id.btnSendNow).setOnClickListener(this);

        etIncrementNumber = findViewById(R.id.etIncrementNumber);
        et_cmd = findViewById(R.id.et_cmd);
        et_uuid = findViewById(R.id.et_uuid);
        et_time = findViewById(R.id.et_time);
        et_notify = findViewById(R.id.et_notify);
        et_uuid_server = findViewById(R.id.et_uuid_server);
        tv_receive_number = findViewById(R.id.tv_receive_number);
        tv_send_number = findViewById(R.id.tv_send_number);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn1) {
            try {
                mNumMax = Integer.parseInt(etIncrementNumber.getText().toString().trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
                mNumMax = 514;
            }
            sendCmd = et_cmd.getText().toString().trim();
            sendCmdB = BleDensityUtil.getInstance().toBytes(sendCmd);
            mHandler.removeMessages(SEND_DATA);
            mHandler.sendEmptyMessage(SEND_DATA);
        } else if (id == R.id.btn_stop) {
            mHandler.removeMessages(SEND_DATA);
        } else if (id == R.id.clear) {
            if (mList != null)
                mList.clear();
            mSendNumber = 0;
            mReceiveNumber = 0;
            tv_receive_number.setText("0");
            tv_send_number.setText("0");
            mHandler.sendEmptyMessage(REFRESH_DATA);
        } else if (id == R.id.btn_uuid) {
            String uuid = et_uuid.getText().toString().trim().toUpperCase(Locale.ENGLISH);
            sendUuid = UuidUtils.getUuid(uuid);
            addLog("设置特征UUID");
        } else if (id == R.id.btn_uuid_server) {
            String uuidServer = et_uuid_server.getText().toString().trim().toUpperCase(Locale.ENGLISH);
            sendUuidServer = UuidUtils.getUuid(uuidServer);
            addLog("设置服务UUID");
        } else if (id == R.id.btn_time) {
            String time = et_time.getText().toString().trim().toUpperCase(Locale.ENGLISH);
            sendTime = Integer.parseInt(time);
            addLog("设置时间间隔(ms):" + sendTime);
            if (mBleDevice != null) {
                mBleDevice.setSendDataInterval(sendTime);
            }
        } else if (id == R.id.btn_notify) {
            String notify = et_notify.getText().toString().trim().toUpperCase(Locale.ENGLISH);
            readNotify(notify, mNotify);
            addLog("设置Notify UUID");
        } else if (id == R.id.btn_notify_status) {
            mNotify = !mNotify;
            ((Button) v).setText("" + mNotify);
        } else if (id == R.id.btn_log) {
            mShowLog = !mShowLog;
            ((Button) v).setText("log:" + (mShowLog ? "Y" : "N"));
        } else if (id == R.id.btnIncrementSend) {
            mIncrementSend = !mIncrementSend;
//                mBleDevice.setMtu(mNumMax);
            ((Button) v).setText("递增发送:" + (mIncrementSend ? "Y" : "N"));
        } else if (id == R.id.btnSendNow) {
            byte[] bytes = BleDensityUtil.getInstance().toBytes(et_cmd.getText().toString().trim());
            SendDataBean sendDataBean = new SendDataBean(bytes, sendUuid, BleConfig.WRITE_DATA, sendUuidServer);
            mBleDevice.sendDataNow(sendDataBean);
        }
    }

    private boolean mNotify = true;

    /**
     * 设置通知
     */
    private void readNotify(String notify, boolean notifyOpen) {
        UUID uuidNotify = UuidUtils.getUuid(notify);
        if (mBleDevice != null && sendUuidServer != null) {
            if (notifyOpen) {
                mBleDevice.setNotify(sendUuidServer, uuidNotify);
            } else {
                mBleDevice.setCloseNotify(sendUuidServer, uuidNotify);
            }

        } else {
            mList.add(TimeUtils.getTime() + "请先设置特征UUID和服务UUID");
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }


    private void addLog(String log) {
        if (mShowLog) {
            mList.add(TimeUtils.getTimeSSS() + log);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }
    //---------------------------------服务---------------------------------------------------


    @Override
    public void onServiceSuccess() {
        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            mBleDevice = mAILinkBleManager.getBleDevice(mAddress);
            CallbackDisIm.getInstance().addListListener(this);
            if (mBleDevice != null) {
                mBleDevice.setConnectPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
                mBleDevice.setOnBleOtherDataListener(this);
                mBleDevice.setOnBleDeviceDataListener(this);
                mBleDevice.setOnBleMtuListener(new OnBleMtuListener() {
                    @Override
                    public void OnMtu(int mtu) {
                        addLog("系统返回MTU:" + mtu);
                    }
                });
            }
        }
    }

    @Override
    public void onServiceErr() {
        BleLog.i(TAG, "服务与界面连接断开");
        //与服务断开连接
        mAILinkBleManager = null;
    }

    @Override
    public void unbindServices() {
        CallbackDisIm.getInstance().removeListener(this);
        if (mBleDevice != null) {
            mBleDevice.disconnect();
            mBleDevice = null;
        }

    }

    //-----------------状态-------------------


    @Override
    public void onConnecting(@NonNull String mac) {
        //TODO 连接中
        BleLog.i(TAG, "连接中");
    }

    @Override
    public void onDisConnected(@NonNull String mac, int code) {
        //TODO 连接断开
        BleLog.i(TAG, "连接断开");
        mList.add(TimeUtils.getTime() + "连接断开");
        mHandler.removeMessages(SEND_DATA);
        mHandler.sendEmptyMessage(REFRESH_DATA);

    }

    @Override
    public void onServicesDiscovered(@NonNull String mac) {
        //TODO 连接成功(获取服务成功)
        BleLog.i(TAG, "连接成功(获取服务成功)");
    }


    @Override
    public void bleOpen() {

    }

    @Override
    public void bleClose() {
        mHandler.removeMessages(SEND_DATA);
        addLog("蓝牙关闭");
        BleLog.i(TAG, "蓝牙未开启,可请求开启");
    }

    //-----------------通知-------------------


    @Override
    public void onNotifyData(String uuid, byte[] hex, int type) {
        if (!mShowLog) {
            return;
        }
        String data = "";
        if (hex != null)
            data = BleStrUtils.byte2HexStr(hex);
        if (type == 100) {
            mList.add(TimeUtils.getTime() + "send->" + data);
        } else {
            mList.add(TimeUtils.getTime() + "notify1->" + data);
            mReceiveNumber += hex.length;
            tv_receive_number.setText(String.valueOf(mReceiveNumber));
        }
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }


    @Override
    public void onNotifyOtherData(String uuid, byte[] hex) {
        if (mBleDevice != null) {
            hex[0] = (byte) (hex[0] + 1);
            SendDataBean sendDataBean = new SendDataBean(hex, BleConfig.UUID_WRITE_AILINK, BleConfig.WRITE_DATA, BleConfig.UUID_SERVER_AILINK);
            mBleDevice.sendDataNow(sendDataBean);
        }
        if (mShowLog) {
            String data = "";
            if (hex != null)
                data = BleStrUtils.byte2HexStr(hex);
            mList.add(TimeUtils.getTime() + "notify2->" + data);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }
        mReceiveNumber += hex.length;
        tv_receive_number.setText(String.valueOf(mReceiveNumber));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        BleLog.i(TAG, "onDestroy");
    }
}
