package com.phlx.anchorcollect.bt;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.phlx.anchorcollect.ble.BleService;
import com.phlx.anchorcollect.event.EventKey;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventUtils;

import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.ConnectCallback;
import cn.wandersnail.bluetooth.Connection;
import cn.wandersnail.bluetooth.EventObserver;

public class BtService extends Service implements EventObserver {

    private static final String TAG = BtService.class.getSimpleName();

    private Connection connection;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        BTManager.getInstance().registerObserver(this);
        Log.e(TAG, "onStartCommand: " + "服务开启了");

        BluetoothDevice device = intent.getParcelableExtra("device");
        connection = BTManager.getInstance().createConnection(device, this);//观察者监听连接状态
        //如果传null，默认使用{@link #SPP_UUID}连接
        connection.connect(null, new ConnectCallback() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "connection.connect: " + "onSuccess");
            }

            @Override
            public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                Log.e(TAG, "connection.connect: " + "onFail--" + errMsg);
            }
        });
        return START_STICKY;
    }

    @Override
    public void onRead(@NonNull BluetoothDevice device, @NonNull byte[] value) {
        Log.e(TAG, "onRead: " + new String(value));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BTManager.getInstance().unregisterObserver(this);
    }
}
