package com.phlx.anchorcollect.ble;

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

import androidx.annotation.NonNull;

import com.phlx.anchorcollect.App;
import com.phlx.anchorcollect.event.EventKey;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventUtils;
import com.uhf.structures.OnBluetoothListener;

import java.util.UUID;

import cn.wandersnail.ble.ConnectionState;
import cn.wandersnail.ble.Device;
import cn.wandersnail.ble.EasyBLE;
import cn.wandersnail.ble.EventObserver;
import cn.wandersnail.ble.Request;
import cn.wandersnail.commons.observer.Observe;
import cn.wandersnail.commons.poster.RunOn;
import cn.wandersnail.commons.poster.Tag;
import cn.wandersnail.commons.poster.ThreadMode;


/**
 * <pre>
 *     author : lei
 *     e-mail : 18600395998@163.com
 *     time   : 2019/04/12
 *     desc   : 蓝牙接收数据服务
 *     version: 1.0
 * </pre>
 */
public class BleService extends Service implements  EventObserver {

    private static final String TAG = BleService.class.getSimpleName();
    private BleManagers bleManagers;

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


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        EasyBLE.getInstance().registerObserver(this);
        bleManagers = BleManagers.from(this);
        EventUtils.post(new EventMsg(EventKey.KEY_BLUETOOTH_CONNECT_SUCCESS,null));
        Log.e(TAG, "onStartCommand: "+"服务开启了" );
        return START_STICKY;

    }



    @Tag("onCharacteristicChanged")
    @RunOn(ThreadMode.BACKGROUND)
    @Observe
    @Override
    public void onCharacteristicChanged(Device device, UUID service, UUID characteristic, byte[] value) {
//        App.getInstance().getLinkage().pushRemoteRFIDData(value);
        Log.e("Data:notify", value.length + "<--" + bytesToHexString(value, value.length));
    }

    /**
     * 连接状态 监听
     *
     * @param device
     */
    @Tag("onConnectionStateChanged")
    @Observe
    @RunOn(ThreadMode.MAIN)
    @Override
    public void onConnectionStateChanged(@NonNull Device device) {
        if (device.getConnectionState() == ConnectionState.DISCONNECTED) {
            EventUtils.post(new EventMsg(EventKey.KEY_BLUETOOTH_CONNECT_FAILED,null));
                EventUtils.post(new EventMsg<>(EventKey.KEY_INVENTORY_STOP, null));

        }
    }

    /**
     * 写入状态监听
     *
     * @param request
     * @param value
     */
    @Tag("onCharacteristicWrite")
    @RunOn(ThreadMode.BACKGROUND)
    @Observe
    @Override
    public void onCharacteristicWrite(@NonNull Request request, @NonNull byte[] value) {
        Log.e("写入状态监听-", "成功写入:" + cn.wandersnail.commons.util.StringUtils.toHex(value, " "));
//        if (uuid_read != null && uuid_notify == null) {
//            bleManagers.readCharacteristic(uuid_service, uuid_read);
//        }
    }

    @Override
    public void onCharacteristicRead(@NonNull Request request, @NonNull byte[] value) {
        if (value.length > 0) {
            App.getInstance().getLinkage().pushRemoteRFIDData(value);
         //   Log.e("Data:read", value.length + "<--" + bytesToHexString(value, value.length));
        }
    }


    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: "+"服务挂掉了" );
        EasyBLE.getInstance().unregisterObserver(this);
    }

    public static String bytesToHexString(byte src[], int length) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0 || length <= 0)
            return null;
        for (int i = 0; i < length && i < src.length; i++) {
            int v = src[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2)
                stringBuilder.append(0);
            stringBuilder.append(hv + " ");
        }
        return stringBuilder.toString().toUpperCase();
    }

}