#include "ble_modem.h"
#include "app_common.h"
#include "host/ble_hs.h"
#include "FreeRTOS.h"
#include "wm_bt_def.h"
#include "wm_bt_app.h"
#include "wm_bt_util.h"
#include "ble_service.h"

//Is needed for the BT off workaround
#include "wm_wifi.h"

bool ble_modem_on(bool bluetoothOnly, bool startService)
{
    int status = BLE_HS_ENOERR;
    bool serviceStartSuccess = true;
    uint8_t uart_no = 0xFF;
    tls_appl_trace_level = TLS_BT_LOG_VERBOSE; //Should be set with a config define

    if(bt_adapter_state == WM_BT_STATE_ON) 
    {
        TLS_BT_APPL_TRACE_VERBOSE("ble modem already on"NEW_LINE);
        return true;
    }

    TLS_BT_APPL_TRACE_DEBUG("ble modem running, uart_no=%d, log_level=%d"NEW_LINE, uart_no,
                            tls_appl_trace_level);
    status = tls_bt_init(uart_no);

    if((status != BLE_HS_ENOERR) && (status != BLE_HS_EALREADY)) 
    {
        TLS_BT_APPL_TRACE_ERROR("%s, tls_bt_init ret:%s"NEW_LINE, __FUNCTION__, tls_bt_rc_2_str(status));
    }
    else
    {
        // If we successfully started the modem, we can set it's working mode. 
        if(bluetoothOnly) 
            tls_rf_bt_mode(true);
        // Start the ble service if it was asked and if it is not yet started
        if(startService && !ble_service_is_started())
            serviceStartSuccess = ble_service_start();
    }

    return ((status == BLE_HS_ENOERR || status == BLE_HS_EALREADY) && serviceStartSuccess) ? true : false;
}

bool ble_modem_off(void)
{
    int status = BLE_HS_ENOERR;
    bool serviceStopSuccess = true;
    TLS_BT_APPL_TRACE_DEBUG("ble modem off"NEW_LINE);

    if(bt_adapter_state == WM_BT_STATE_OFF)
    {
        TLS_BT_APPL_TRACE_VERBOSE("ble modem already off"NEW_LINE);
        return TLS_BT_STATUS_SUCCESS;
    }

    if(ble_service_is_started())
    {
        serviceStopSuccess = ble_service_stop();
    }

    // Let's make a busy wait on the status of the ble service:
    uint8_t timeout = 0;
    while(ble_service_is_started())
    {
        tls_os_time_delay(pdMS_TO_TICKS(5));

        // Service is stuck ? waiting up to 300 ms for it to stop
        if(++timeout > 60)
        {
            TLS_BT_APPL_TRACE_ERROR("%s, ble_service_stop timeout "NEW_LINE, __FUNCTION__);
            return serviceStopSuccess;
        }
    };

    status = tls_bt_deinit();

    if((status != BLE_HS_ENOERR) && (status != BLE_HS_EALREADY)) {
        TLS_BT_APPL_TRACE_ERROR("%s, tls_bt_deinit ret:%s"NEW_LINE, __FUNCTION__, tls_bt_rc_2_str(status));
    }

    if(status != BLE_HS_EALREADY)
    {
        //Starting a wifi scan really stops the BT modem ?? Why ? I don't know
        tls_wifi_scan();
    }

    return ((status == BLE_HS_ENOERR || status == BLE_HS_EALREADY) && serviceStopSuccess) ? true : false;
}

bool is_ble_modem_on(void)
{
    if(bt_adapter_state == WM_BT_STATE_OFF || bt_system_action != WM_BT_SYSTEM_ACTION_IDLE)
        return false;
    return true;
}
