#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/gap.h>
#include <zephyr/bluetooth/hci.h>

static int start_advertising(struct bt_le_ext_adv *adv)
{
	int err;

	printk("Starting Extended Advertising\n");
	err = bt_le_ext_adv_start(adv, BT_LE_EXT_ADV_START_DEFAULT);
	if (err) {
		printk("Failed to start extended advertising (err %d)\n", err);
	}

	return err;
}

static const struct bt_data ad[] = {
	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
};

static int create_advertising_set(struct bt_le_ext_adv **adv)
{
    int err;


    struct bt_le_adv_param param = {
        .id = BT_ID_DEFAULT,
        .sid = 0,
        .secondary_max_skip = 0,
        .options = BT_LE_ADV_OPT_EXT_ADV | BT_LE_ADV_OPT_USE_IDENTITY | BT_LE_ADV_OPT_NO_2M,
        .interval_min = 3200, // 2000 ms in 0.625 ms steps
        .interval_max = 3200,
        .peer = NULL,
    };

    err = bt_le_ext_adv_create(&param, NULL, adv);
    if (err) {
        printk("Failed to create advertising set (err %d)\n", err);
        return err;
    }

    return 0;
}

int main(void)
{
	int err;
	struct bt_le_ext_adv *adv;

	printk("Starting main loop\n");

	/* Initialize the Bluetooth Subsystem */
	err = bt_enable(NULL);
	if (err) {
		printk("Bluetooth init failed (err %d)\n", err);
		return err;
	}
	
	/* Create a nonconnectable advertising set with the custom parameters */
	err = create_advertising_set(&adv);
	if (err) {
		return err;
	}

	/* Set advertising data to have complete local name set */
	err = bt_le_ext_adv_set_data(adv, ad, ARRAY_SIZE(ad), NULL, 0);
	if (err) {
		printk("Failed to set advertising data (err %d)\n", err);
		return 0;
	}

	err = start_advertising(adv);
	if (err) {
		return err;
	}

    /* Just keep running, no connections possible */
    for (;;) {
        k_sleep(K_SECONDS(1));
    }

    return err;
}