#include "ble_sn2model.h"
#include "ble.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

DEV_MODEL model_tbl[] = SN2MODEL_MAP_TBL;

void hex_to_str(const uint8_t *src, uint8_t *dest, int32_t src_len)
{
    int32_t i;
    uint8_t tmp[3];

    for (i = 0; i < src_len; i++)
    {
        sprintf(tmp, "%02X", src[i]);
        memcpy(&dest[i * 2], tmp, 2);
    }

    return;
}

void str_to_hex(const uint8_t *src, uint8_t *dest, int32_t src_len)
{
    int32_t i;
    uint8_t high_byte, low_byte;

    for (i = 0; i < src_len; i += 2)
    {
        high_byte = toupper(src[i]);
        low_byte  = tolower(src[i + 1]);

        if (high_byte > 0x39)
        {
            high_byte -= 0x37;
        }
        else
        {
            high_byte -= 0x30;
        }

        if (low_byte > 0x39)
        {
            low_byte -= 0x37;
        }
        else
        {
            low_byte -= 0x30;
        }

        dest[i / 2] = (high_byte << 4) | low_byte;
    }

    return;
}

int32_t str_sn_2_model(uint8_t *str_sn, uint8_t *model)
{
    for (int32_t i = 0; i < sizeof(model_tbl) / sizeof(DEV_MODEL); i++)
    {
        if (strncmp(model_tbl[i].prefix, &str_sn[4], MODEL_LEN) == 0)
        {
            strcpy(model, model_tbl[i].model);
            return 0;
        }
    }
    return 1;
}

int32_t hex_sn_2_model(uint8_t *hex_sn, uint8_t *model)
{
    uint8_t str_sn[SN_LEN * 2 + 1] = {0};
    hex_to_str(hex_sn, str_sn, SN_LEN);
    return str_sn_2_model(str_sn, model);
}

int32_t sn_2_model(uint8_t *sn, int32_t sn_type, uint8_t *model)
{
    if (sn_type == 0)
    {
        return str_sn_2_model(sn, model);
    }
    else
    {
        return hex_sn_2_model(sn, model);
    }
}