#include "proto_can_adp.h"
#include "prot_transf.h"
#if 1 // olipower BSM支持的一些can帧解析函数
static int olipower_0x80003221(proto_can_poll *p)
{
    long long cur_ms = 0;
    uint8_t *buff = p->buff.buff;
    tag_value_t tag_value = {0};
    //
    int index = (buff[0] | (buff[1] << 8)) * 3;
    if ((index + 3) > p->tag_sum)
    {
        proto_syslog(LOG_ERR, "0x80003221 tag sum:%d, cur index:%d", p->tag_sum, index);
        return -1;
    }

    cur_ms = clock_get_ms();
    tag_value.value.to_int = buff[2] | (buff[3] << 8);
    proto_set_tag(p->p_tag[index], tag_value, cur_ms);
    tag_value.value.to_int = buff[4] | (buff[5] << 8);
    proto_set_tag(p->p_tag[index + 1], tag_value, cur_ms);
    tag_value.value.to_int = buff[6] | (buff[7] << 8);
    proto_set_tag(p->p_tag[index + 2], tag_value, cur_ms);
    abnormal_log_match_record(p->p_tag, p->tag_sum, p->buff.buff, p->dlc, (char *)p->buff.buff, p->dlc);
    return 0;
}

static int olipower_0x80003231(proto_can_poll *p)
{
    long long cur_ms = 0;
    uint8_t *buff = p->buff.buff;
    tag_value_t tag_value = {0};
    //
    int index = (buff[0] | (buff[1] << 8)) * 3;
    if ((index + 3) > p->tag_sum)
    {
        proto_syslog(LOG_ERR, "0x80003231 tag sum:%d, cur index:%d", p->tag_sum, index);
        return -1;
    }

    cur_ms = clock_get_ms();
    tag_value.value.to_int = buff[2] | (buff[3] << 8);
    proto_set_tag(p->p_tag[index], tag_value, cur_ms);
    tag_value.value.to_int = buff[4] | (buff[5] << 8);
    proto_set_tag(p->p_tag[index + 1], tag_value, cur_ms);
    tag_value.value.to_int = buff[6] | (buff[7] << 8);
    proto_set_tag(p->p_tag[index + 2], tag_value, cur_ms);
    abnormal_log_match_record(p->p_tag, p->tag_sum, p->buff.buff, p->dlc, (char *)p->buff.buff, p->dlc);
    return 0;
}

static can_frame_handle_map olipower_handle_map[] = {
    {.id = 0x80003221, .fun = olipower_0x80003221},
    {.id = 0x80003231, .fun = olipower_0x80003231},
};

static proto_can_adp olipower_adp = {
    .name = "olipower",
    .handle_map = olipower_handle_map,
    .handle_map_size = sizeof(olipower_handle_map) / sizeof(olipower_handle_map[0])};
#endif
/**********************************************************/
static proto_can_adp *can_adp_arr[] = {
    &olipower_adp};

const proto_can_adp *find_proto_can_adp(const char *name)
{
    int sum = sizeof(can_adp_arr) / sizeof(can_adp_arr[0]);
    for (int i = 0; i < sum; i++)
    {
        if (strcmp(can_adp_arr[i]->name, name) == 0)
        {
            return can_adp_arr[i];
        }
    }

    return NULL;
}

int (*find_proto_can_adp_handle(const proto_can_adp *adp, uint32_t id))(proto_can_poll *)
{
    int sum = adp->handle_map_size;
    for (int i = 0; i < sum; i++)
    {
        if (adp->handle_map[i].id == id)
        {
            return adp->handle_map[i].fun;
        }
    }

    return NULL;
}
