#include "t1001.h"
#include "omw_dbg.h"
#include "t1001_vtimer.h"
#include "t1001_sleep.h"
#include "sys_timeout.h"
#include "hci_core.h"
#include "v0/controller/hci_driver.h"
#include "v0/drivers/hci_driver.h"

#ifdef OMW_HAS_SCH
#include "omw_rtos.h"
#endif

void bt_ready(int err);
void bt_att_tx_polling();

SleepModes local_sleep_mode = SLEEPMODE_CPU_HALT;

#ifdef ENABLE_HCI_LOG
int hci_driver_send_and_log(simple_buf_t *buf);
int hci_driver_open_and_log(void* cb);

static const struct bt_hci_driver drv = {
        #ifndef OMW_COMID_PATCH
        .open = hci_driver_open_and_log,
        #else
        .open = hci_driver_open_patch,
        #endif
        .send = hci_driver_send_and_log,
        .polling = hci_driver_polling_work,
};

static bt_hci_controller_send_cb_t bt_controller_send_cb_org_log;
void hci_driver_rcv_pactch(simple_buf_t *buf)
{
	if (BT_BUF_EVT == bt_buf_get_type(buf))
	{
		printf("EVT <= ");
	}else {
		printf("ACL <= ");
	}
	
	for (uint8_t i = 0; i<buf->b.len; i++) {
		printf("%02X ",buf->b.data[i]);
	}
	printf("\r\n");
    if (bt_controller_send_cb_org_log != NULL)
        bt_controller_send_cb_org_log(buf);
}

int hci_driver_open_and_log(void* cb)
{
    hci_driver_open(hci_driver_rcv_pactch);

    bt_controller_send_cb_org_log = cb;
    return 0;
}


int hci_driver_send_and_log(simple_buf_t *buf)
{
	if (BT_BUF_CMD == bt_buf_get_type(buf))
	{
		printf("CMD => ");
	}else {
		printf("ACL => ");
	}	
	for (uint8_t i = 0; i<buf->b.len; i++) {
		printf("%02X ",buf->b.data[i]);
	}
	printf("\r\n");
    return hci_driver_send(buf);	
}
#else
static const struct bt_hci_driver drv = {
        #ifndef OMW_COMID_PATCH
        .open = hci_driver_open,
        #else
        .open = hci_driver_open_patch,
        #endif
        .send = hci_driver_send,
        .polling = hci_driver_polling_work,
};
#endif


static void hci_driver_init(void)
{
    bt_hci_driver_register(&drv);
}


void omw_host_work_polling()
{
    bt_polling_work();

    bt_att_tx_polling();

    omw_hw_chk_and_en_irq();
}

#ifdef OMW_HAS_SCH
static void omw_host_task(void)
{
    while(1) {
        omw_host_work_polling();

        #ifdef OMW_EN_WDG
        FEED_WTD(OMW_FEED_WDG_TIME);
        #endif
    }
}
#endif

void omw_host_init()
{
    printf("v0 host init!\n");

    omw_set_irq_prio(RTC_IRQn, IRQ_HIGH_PRIORITY);
    omw_enable_irq(RTC_IRQn);

    hci_driver_init();

    bt_enable(bt_ready);

    #ifdef OMW_HAS_SCH
    omw_rtos_add_task(omw_host_task, OMW_RTOS_PRO_UP_MID, OMW_HOST_TASK_SP_SS, OMW_CTRL_ARG_FLAG); //v0 host + v0 ctrl, use OMW_CTRL_ARG_FLAG
    #endif
}
