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 android.widget.Toast;

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

import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.ble.BleService;
import com.phlx.anchorcollect.event.EventKey;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventTag;
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;
import cn.wandersnail.commons.util.ToastUtils;
import me.goldze.mvvmhabit.bus.RxBus;

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");
                EventMsg eventMsg = new EventMsg();
                eventMsg.setAction(EventTag.EVENT_BT_SUCC);
                RxBus.getDefault().post(eventMsg);
            }

            @Override
            public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                Log.e(TAG, "connection.connect: " + "onFail--" + errMsg);
                EventMsg eventMsg = new EventMsg();
                eventMsg.setAction(EventTag.EVENT_BT_FAIL);
                RxBus.getDefault().post(eventMsg);
            }
        });
        return START_STICKY;
    }

    @Override
    public void onRead(@NonNull BluetoothDevice device, @NonNull byte[] value) {

        String data = new String(value);
        Log.e(TAG, "onRead: " + data);
//        ToastUtils.showShort("onRead: " + data);

        String weightData = data.substring(data.indexOf("wn") + 3, data.indexOf("kg"));
        EventMsg eventMsg = new EventMsg();
        eventMsg.setAction(Configs.currentEvent);
        eventMsg.setObj(weightData);
        RxBus.getDefault().post(eventMsg);
    }

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