#include "l2cap.h"
#include "host/conn.h"
#include "host/att.h"
#include "base/bt_errno.h"

#include "utils/byteorder.h"

#define LOG_MODULE_NAME l2cap_ext
////#include "bt_log.h"


#if defined(CONFIG_BT_CONN)

static simple_buf_t *l2cap_create_le_sig_pdu(simple_buf_t *buf,
					       uint8_t code, uint8_t ident,
					       uint16_t len)
{
	struct bt_l2cap_sig_hdr *hdr;
	simple_buf_pool_t *pool = NULL;

	buf = bt_l2cap_create_pdu(pool, 0);
	if (!buf) {
		//LOG_ERR("Unable to allocate buffer for op 0x%02x", code);
		return NULL;
	}

	hdr = simple_buf_add(buf, sizeof(*hdr));
	hdr->code = code;
	hdr->ident = ident;
	hdr->len = sys_cpu_to_le16(len);

	return buf;
}

static uint8_t l2cap_ident;

static uint8_t get_ident(void)
{
    l2cap_ident++;
    /* handle integer overflow (0 is not valid) */
    if (!l2cap_ident)
    {
        l2cap_ident++;
    }

    return l2cap_ident;
}

int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param)
{
    struct bt_l2cap_conn_param_req *req;
    simple_buf_t *buf;
    int err;

    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, get_ident(), sizeof(*req));
    if (!buf)
    {
        return -ENOMEM;
    }

    req = simple_buf_add(buf, sizeof(*req));
    req->min_interval = sys_cpu_to_le16(param->interval_min);
    req->max_interval = sys_cpu_to_le16(param->interval_max);
    req->latency = sys_cpu_to_le16(param->latency);
    req->timeout = sys_cpu_to_le16(param->timeout);

    err = bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
    if (err)
    {
        simple_buf_free(buf);
        return err;
    }

    return 0;
}

#endif
