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.callback.BtMsgListener;

import java.nio.charset.StandardCharsets;

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

    /**
     * 消息回调
     */
    private final BtMsgListener mMsgListener = new BtMsgListener() {
        @Override
        public void socketNotify(int state, @NonNull String msg) {
            super.socketNotify(state, msg);
            // 当客户端断开连接时，需要重新开始监听客户端的连接
            if (state == BtMsgListener.DISCONNECTED) {
                if (classicServer != null) {
                    classicServer.listen();
                }
            } else if (state == BtMsgListener.MSG) {
                // 服务端只关心内容消息
                // 将内容消息透传给外部调用者
                if (msgListener != null) {
                    msgListener.socketNotify(state, msg);
                }
            }
        }
    };

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

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

        Log.i(TAG, "initialize BluetoothManager");
        classicServer = new BluetoothClassicServer(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (classicServer != null) {
            classicServer.setListener(mMsgListener);
            classicServer.listen();
        }
        return new ClassicReceiverBinder();
    }

    public class ClassicReceiverBinder extends Binder {
        public BTCReceiverService getService() {
            return BTCReceiverService.this;
        }
    }

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

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

    @Override
    public boolean onUnbind(Intent intent) {
        if (classicServer != null) {
            classicServer.setListener(null);
            classicServer.close();
        }
        return super.onUnbind(intent);
    }
}
