package jp.agentec.abook.abv.cl.util;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.util.UUID;

import jp.agentec.abook.abv.bl.common.log.Logger;

/**
 * SPP通信のbluetoothの接続スレッド
 */
public class SppBluetoothConnectThread extends Thread {
    protected String TAG = "SppBluetoothConnectThread";

    // "00001101-0000-1000-8000-00805f9b34fb" = SPP (シリアルポートプロファイル) の UUID.
    public static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    private BluetoothSocket mSocket;
    private bluetoothConnectThreadListener mListener;

    private BluetoothDevice mBluetoothDevice;

    public interface bluetoothConnectThreadListener {
        void onConnect(BluetoothSocket socket);  // 接続リスナ
        void onFail();
    }

    public SppBluetoothConnectThread(BluetoothDevice device, bluetoothConnectThreadListener listener) {
        mListener = listener;
        mBluetoothDevice = device;
        try {
            mSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
        } catch (IOException e) {
            Logger.e(TAG, e);
        }
    }

    @Override
    public void run() {
        if (mSocket == null) {
            Logger.e(TAG, "socket is null");
            return;
        }
        try {
            mSocket.connect();
        } catch (IOException e) {
            Logger.e(TAG, e);
            try {
                if (mSocket == null) {
                    return;
                }
                mSocket.close();
            } catch (IOException e1) {
                Logger.e(TAG, e);
            }
            mListener.onFail();
            return;
        }

        mListener.onConnect(mSocket);
        Logger.i(TAG, "Bluetooth connecting.");
    }

    public boolean isConnecting() {
        return mSocket.isConnected();
    }

    /**
     * ソケットを初期化する
     */
    public void finish() {
        if (mSocket == null) {
            return;
        }
        try {
            mSocket.close();
        } catch (IOException e) {
            Logger.e(TAG, e);
        }
        mSocket = null;
    }

    public String getConnectedAddress() {
        if (mBluetoothDevice == null) {
            return null;
        }
        return mBluetoothDevice.getAddress();
    }
}