#include "sdk_config.h"
#include "ble.h"
#include "ble_conn_params.h"
#include "ble_gap.h"
#include "gap.h"
#include "error.h"
#include "nrf_log.h"

#define DEVICE_NAME       "ANCS2"                         /**< Name of the device. Will be included in the advertising data. */
#define STATIC_PASSKEY    "123456"                        /**< Static passkey. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_1_25_MS) /**< Minimum acceptable connection interval (0.5 seconds). */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(30, UNIT_1_25_MS) /**< Maximum acceptable connection interval (1 second). */
#define SLAVE_LATENCY     0                               /**< Slave latency. */
#define CONN_SUP_TIMEOUT  MSEC_TO_UNITS(3000, UNIT_10_MS) /**< Connection supervisory time-out (4 seconds). */

static ble_opt_t _gStaticPasskeyOption;	/**< Pointer to the struct containing static pin option. */

/**@brief Function for initializing GAP connection parameters.
 *
 * @details Use this function to set up all necessary GAP (Generic Access Profile)
 *          parameters of the device. It also sets the permissions and appearance.
 */
int gapParamsInit(void) {
    ret_code_t              errCode;
    ble_gap_conn_params_t   gapConnParams;
    ble_gap_conn_sec_mode_t secMode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&secMode);

    errCode = sd_ble_gap_device_name_set(&secMode, (const uint8_t *)DEVICE_NAME, strlen(DEVICE_NAME));
    if (errCode != NRF_SUCCESS) {
        NRF_LOG_WARNING("sd_ble_gap_device_name_set() failed, errCode=0x%x", errCode);
        return ERROR_GAP_INITIALIZE_FAIL;
    }

    memset(&gapConnParams, 0, sizeof(gapConnParams));

    gapConnParams.min_conn_interval = MIN_CONN_INTERVAL;
    gapConnParams.max_conn_interval = MAX_CONN_INTERVAL;
    gapConnParams.slave_latency     = SLAVE_LATENCY;
    gapConnParams.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    errCode = sd_ble_gap_ppcp_set(&gapConnParams);
    if (errCode != NRF_SUCCESS) {
        NRF_LOG_WARNING("sd_ble_gap_ppcp_set() failed, errCode=0x%x", errCode);
        return ERROR_GAP_INITIALIZE_FAIL;
    }

    uint8_t passkey[] = STATIC_PASSKEY;
	_gStaticPasskeyOption.gap_opt.passkey.p_passkey = passkey;
	errCode = sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &_gStaticPasskeyOption);
	if (errCode != NRF_SUCCESS) {
        NRF_LOG_WARNING("sd_ble_opt_set() failed, errCode=0x%x", errCode);
        return ERROR_GAP_INITIALIZE_FAIL;
    }

    return 0;
}


