/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-04-14     chenyong     first version
 */

#include <at.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "sr_log.h"

static char send_buf[AT_CMD_MAX_LEN];
static srSize_t last_cmd_len = 0;

/**
 * dump hex format data to console device
 *
 * @param name name for hex object, it will show on log header
 * @param buf hex buffer
 * @param size buffer size
 */
void at_print_raw_cmd(const char *name, const char *buf, srSize_t size)
{
#define __is_print(ch)       ((unsigned int)((ch) - ' ') < 127u - ' ')
#define WIDTH_SIZE           32

    srSize_t i, j;

    for (i = 0; i < size; i += WIDTH_SIZE)
    {
        SR_PRINTF("[D/AT] %s: %04X-%04X: ", name, i, i + WIDTH_SIZE);
        for (j = 0; j < WIDTH_SIZE; j++)
        {
            if (i + j < size)
            {
                SR_PRINTF("%02X ", (unsigned char)buf[i + j]);
            }
            else
            {
                SR_PRINTF("   ");
            }
            if ((j + 1) % 8 == 0)
            {
                SR_PRINTF(" ");
            }
        }
        SR_PRINTF("  ");
        for (j = 0; j < WIDTH_SIZE; j++)
        {
            if (i + j < size)
            {
                SR_PRINTF("%c", __is_print(buf[i + j]) ? buf[i + j] : '.');
            }
        }
        SR_PRINTF("\n");
    }
}

const char *at_get_last_cmd(srSize_t *cmd_size)
{
    *cmd_size = last_cmd_len;
    return send_buf;
}

SR_WEAK srSize_t at_utils_send(SR_DEVICE_T *dev,
                                srOff_t    pos,
                                void *buffer,
                                srSize_t   size)
{
    //return rt_device_write(dev, pos, buffer, size);
	  return SR_HalUartWrite(dev, buffer, size);
}

srSize_t at_vprintf(SR_DEVICE_T *device, const char *format, va_list args)
{
    last_cmd_len = vsnprintf(send_buf, sizeof(send_buf), format, args);
    if(last_cmd_len > sizeof(send_buf))
        last_cmd_len = sizeof(send_buf);

#ifdef AT_PRINT_RAW_CMD
    at_print_raw_cmd("sendline", send_buf, last_cmd_len);
#endif

    return at_utils_send(device, 0, send_buf, last_cmd_len);
}

srSize_t at_vprintfln(SR_DEVICE_T *device, const char *format, va_list args)
{
    srSize_t len;

    last_cmd_len = vsnprintf(send_buf, sizeof(send_buf) - 2, format, args);
    if(last_cmd_len > sizeof(send_buf) - 2)
        last_cmd_len = sizeof(send_buf) - 2;
    memcpy(send_buf + last_cmd_len, "\r\n", 2);

    len = last_cmd_len + 2;

#ifdef AT_PRINT_RAW_CMD
    at_print_raw_cmd("sendline", send_buf, len);
#endif

    return at_utils_send(device, 0, send_buf, len);
}
