package com.phlx.anchor_collect_flutter.ble;


import static com.phlx.anchor_collect_flutter.ble.Configs.uuid_service;
import static com.phlx.anchor_collect_flutter.ble.Configs.uuid_write;

import android.app.Service;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

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

import com.phlx.anchor_collect_flutter.RfidPlugin;
import com.uhf.structures.OnBluetoothListener;

import java.util.List;
import java.util.UUID;

import cn.wandersnail.ble.Connection;
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.ble.RequestBuilder;
import cn.wandersnail.ble.RequestBuilderFactory;
import cn.wandersnail.ble.RequestType;
import cn.wandersnail.ble.callback.MtuChangeCallback;
import cn.wandersnail.ble.callback.NotificationChangeCallback;
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 OnBluetoothListener, EventObserver {

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

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

    @Override
    public void onCreate() {
        super.onCreate();
        RfidPlugin.getLinkage().setOnBluetoothListener(this);
        EasyBLE.getInstance().registerObserver(this);
        bleManagers = BleManagers.from(this);
        Log.e(TAG, "onCreate: -----服务起了" );
    }

    @Override
    public void getBluetoothData(byte[] bytes) {
        if (bytes != null && bytes.length > 0) {
            bleManagers.writeCharacteristic(uuid_service, uuid_write, bytes);
            Log.e("Data:Send", bytes.length + "<--" + bytesToHexString(bytes, bytes.length));
        }
    }


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

    /**
     * 连接状态 监听
     *
     * @param device
     */


    /**
     * 写入状态监听
     *
     * @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) {
            RfidPlugin.getLinkage().pushRemoteRFIDData(value);
            //   Log.e("Data:read", value.length + "<--" + bytesToHexString(value, value.length));
        }
    }


    @Override
    public void 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();
    }


}