package com.device.comm.mylibrary;

import android.bluetooth.BluetoothGatt;
import android.util.Log;

/**
 * Created by lvwang2002 on 16/1/23.
 */
public class BleDeviceConnect {
    private String TAG =  "BLE_DEVICE_CONNECT";

    private BleDeviceManager mDeviceManager;
    private BluetoothGatt m_gatt;
    private BleDevice mDevice;



    public  BleDeviceConnect(BleDeviceManager deviceManager,BleDevice device){
        this.mDeviceManager = deviceManager;
        this.mDevice = device;
    }

    public BluetoothGatt getGatt(){
        return m_gatt;
    }

    synchronized public BleDevice.ConnectResultState execute() {
        if( mDevice.isNativelyConnected() ) {
            RNLog.d(TAG,"Already connected!");

//            redundant();
            return BleDevice.ConnectResultState.AlreadyConnected;
        }

        if( mDevice.isNativelyConnecting() ) {
            // nothing to do

            return BleDevice.ConnectResultState.AlreadyConnecting;
        }

//        getManager().ASSERT(!getDevice().m_nativeWrapper.isNativelyDisconnecting());


        final boolean useAutoConnect = mDevice.shouldUseAutoConnect();

//        m_autoConnectUsage = useAutoConnect ? AutoConnectUsage.USED : AutoConnectUsage.NOT_USED;



        m_gatt = mDevice.getBluetoothDevice().connectGatt(mDeviceManager.getContext(), false, mDevice.deviceGattCallback);
//        m_gatt = mDevice.getBluetoothDevice().connectGatt(mDeviceManager.getContext(),false,mDevice.deviceGattCallback, BluetoothDevice.TRANSPORT_AUTO);
        if( m_gatt == null ){
            return  BleDevice.ConnectResultState.TryConnectFailed;
        } else {
            //--- DRK > TODO: Don't really like this here...better would be if task listener handled this but I always
            //---				want this gatt instance registered as soon as possible.
//            getDevice().m_nativeWrapper.updateGattInstance(getGatt());
            return  BleDevice.ConnectResultState.TryConnectingSuccessful;
        }
    }

    public void closeGatt(boolean disconnectAlso) {
        if( m_gatt == null )  return;

        final BluetoothGatt gatt = m_gatt;
        try {
            m_gatt.disconnect();
            m_gatt.close();

            mDeviceManager.getMainUpdateLoop().postDelay(new Runnable() {
                @Override
                public void run() {
                    try {
                        gatt.disconnect();
                        gatt.close();
                    }catch(NullPointerException e) {
                        RNLog.d(TAG,"关闭出现异常2");
                    }
                }
            },5000);
        }
        catch(NullPointerException e) {
            RNLog.d(TAG,"关闭出现异常1");
        }

        m_gatt = null;
    }
}
