package com.example.chemical.utils.bluetooth;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.example.chemical.utils.Tool;
import com.kongzue.dialogx.dialogs.PopTip;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.UUID;

public enum BluetoothTool {
    INSTANCE;
    BluetoothAdapter bluetoothAdapter;
    private UUID uuid;
    private byte[] buffer = new byte[1024];
    private BluetoothDevice bluetoothDevice;
    private BluetoothSocket bluetoothSocket;
    private InputStream inputStream;

    private BluetoothTool() {
        uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            BluetoothManager bluetoothManager = Utils.getApp().getSystemService(BluetoothManager.class);
            bluetoothAdapter = bluetoothManager.getAdapter();
        } else {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
    }

    @SuppressLint("MissingPermission")
    public void connect(BluetoothCallBack bluetoothCallBack) {
        if (!bluetoothAdapter.isEnabled()) {
            Tool.INSTANCE.setBluetooth(true);
        }
        bluetoothDevice = getWeighDevice();
        if (null == bluetoothDevice) {
            bluetoothCallBack.connectFailed("未找到蓝牙称");
            return;
        }
        try {
            bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
            bluetoothSocket.connect();
            inputStream = bluetoothSocket.getInputStream();
            int bytesRead;
            String weight = "";
            while (null != bluetoothSocket && bluetoothSocket.isConnected() && null != inputStream && (bytesRead = inputStream.read(buffer)) != -1) {
                // 处理读取的数据
                String data = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                String[] split = data.split("\n", -1);
                if (split.length > 0) {
                    String line = split[0].trim();
                    if (!weight.equals(line)) {
                        weight = line;
                        bluetoothCallBack.callBack(weight);
                    }
                }
                Thread.sleep(1);
            }
        } catch (Exception e) {
            disconnect();
            LogUtils.e(Log.getStackTraceString(e));
        }
    }

    public void disconnect() {
        if (null != bluetoothDevice) {
            bluetoothDevice = null;
        }
        if (null != bluetoothSocket && bluetoothSocket.isConnected()) {
            try {
                inputStream.close();
                inputStream = null;
                bluetoothSocket.close();
                bluetoothSocket = null;
            } catch (Exception e) {
                LogUtils.e(Log.getStackTraceString(e));
            }
        }
    }

    public interface BluetoothCallBack {
        void callBack(String weight);

        void connectFailed(String msg);
    }

    @SuppressLint("MissingPermission")
    private BluetoothDevice getWeighDevice() {
        if (null != bluetoothDevice) {
            return bluetoothDevice;
        }
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (!pairedDevices.isEmpty()) {
            // There are paired devices. Get the name and address of each paired device.
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                if ("HF-18".equals(deviceName)) {
                    return device;
                }
            }
        }
        return null;
    }
}
