package com.common.bluetooth.service.bt;

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

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

import com.common.bluetooth.BtConstants;
import com.common.bluetooth.callback.BtMsgListener;

/**
 * 经典蓝牙服务端
 *
 * @author wangym
 * @since 2021-10-29
 */
public class BTCClientService extends Service {
    private static final String TAG = "BTCClientService";
    /**
     * 检点蓝牙服务端
     */
    private BluetoothClassicClient classicClient;

    /**
     * 消息回调
     */
    private final BtMsgListener mMsgListener = new BtMsgListener() {
        @Override
        public void messageReceive(int state, @NonNull String msg) {
            super.messageReceive(state, msg);
            // 将内容消息透传给外部调用者
            if (msgListener != null) {
                msgListener.messageReceive(state, msg);
            }
        }
    };

    /**
     * 消息回调
     */
    private BtMsgListener msgListener = null;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "initialize BluetoothManager");
        classicClient = BluetoothClassicClient.getInstance(this.getApplication());
        classicClient.checkBtDevice(BtConstants.BLUETOOTH_TYPE.CLASSIC);
    }

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

    public class ClassicClientBinder extends Binder {
        public BTCClientService getService() {
            return BTCClientService.this;
        }
    }

    public void setMsgReceiveListener(BtMsgListener listener) {
        msgListener = listener;
    }

    public void connect(String mac) {
        if (classicClient == null) {
            Log.e(TAG, "classicClient not init success");
            return;
        }
        classicClient.setListener(mMsgListener);
        classicClient.connect(mac);
    }

    /**
     * 断开连接
     * @param mac mac地址
     */
    public void disconnect(String mac) {
        classicClient.close();
    }

    /**
     * 向客户端发送通知
     *
     * @param msg 消息
     */
    public void write(byte[] msg) {
        Log.i(TAG, "write msg = " + new String(msg));
        if (classicClient != null && msg != null) {
            Log.i(TAG, "---send msg start---");
            classicClient.sendMsg(msg);
            Log.i(TAG, "---send msg end---");
        } else {
            Log.e(TAG, "got msg null");
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        classicClient.close();
        return super.onUnbind(intent);
    }
}
