#include <dk_buttons_and_leds.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/settings/settings.h>

LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);

// Advertising parameter
static const struct bt_data ad[] = {
	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, (sizeof(CONFIG_BT_DEVICE_NAME) - 1)),
};
static const struct bt_data sd[] = {
	BT_DATA_BYTES(BT_DATA_UUID128_ALL, 0x84, 0xaa, 0x60, 0x74, 0x52, 0x8a, 0x8b, 0x86, 0xd3, 0x4c, 0xb7, 0x1d, 0x1d, 0xdc, 0x53, 0x8d),				// SMP
};

int main(void)
{
	int err;
	bool led0_on = false;

	struct bt_le_adv_param adv_param = *BT_LE_ADV_PARAM(
		BT_LE_ADV_OPT_CONNECTABLE,
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		NULL
	);
	struct bt_le_ext_adv *ext_adv;
	struct bt_le_ext_adv_start_param ext_adv_start_param = {0};

	err = dk_leds_init();
	if (err) {
		LOG_ERR("Failed to initialize led[s](%d)", err);
		return -1;
	}

	err = bt_enable(NULL);
	if (err) {
		LOG_ERR("Failed to start bluetooth.(%d)", err);
		return -1;
	}
	LOG_INF("Bluetooth controller has been initialized.");

	// Advertising
#if defined(CONFIG_BT_EXT_ADV)
	// Undirected Extended Advertising
	LOG_INF("Start undirected advertising with extension.");

	// Fast Advertising with extension
	adv_param = *BT_LE_ADV_PARAM(
		BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | BT_LE_ADV_OPT_EXT_ADV,
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		NULL
	);

	err = bt_le_ext_adv_create(&adv_param, NULL, &ext_adv);
	if (err) {
		LOG_ERR("Failed to create advertiser set.(%d)", err);
		return -1;
	}
	err = bt_le_ext_adv_set_data(ext_adv, ad, ARRAY_SIZE(ad), NULL, 0);
	if (err) {
		LOG_ERR("Failed to set advertising data.(%d)", err);
		return -1;
	}
	err = bt_le_ext_adv_start(ext_adv, &ext_adv_start_param);
	if (err) {
		LOG_ERR("Failed to start advertising.(%d)", err);
		return -1;
	}
#else
	// Undirected Advertising
	LOG_INF("Start undirected advertising.");

	// Fast Advertising
	adv_param = *BT_LE_ADV_PARAM(
		BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME,
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		0x0050,	  // 0x0050(80) * 0.625 = 50(msec)
		NULL
	);

	err = bt_le_adv_start(&adv_param, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
	if (err) {
		LOG_ERR("Failed to start advertising.(%d)", err);
		return -1;
	}
#endif
printk("build time: " __DATE__ " " __TIME__"\n");
	while (true) {
		if (led0_on) {
			err = dk_set_led_on(0);
			led0_on = false;
		} else {
			err = dk_set_led_off(0);
			led0_on = true;
		}
		k_sleep(K_MSEC(500));
	}
}
