#include "ltrsrv_params.h"
#include "ltrsrv_defs.h"
#include "ltrsrv_log.h"

static const t_ltrsrv_str_tbl f_param_names[] = {
    {LTRD_PARAM_ETH_CRATE_POLL_TIME, "Ethernet crate polling time"},
    {LTRD_PARAM_ETH_CRATE_CON_TOUT, "Ethernet crate connection time"},
    {LTRD_PARAM_ETH_CRATE_CTLCMD_TOUT, "Ethernet crate control command timeout"},
    {LTRD_PARAM_ETH_INTF_CHECK_TIME, "Ethernet interfaces check interval"},
    {LTRD_PARAM_ETH_RECONNECTION_TIME, "Ethernet crate reconnection time"},
    {LTRD_PARAM_MODULE_SEND_BUF_SIZE, "Module send buffer size"},
    {LTRD_PARAM_MODULE_RECV_BUF_SIZE, "Module receive buffer size"}
};

extern int ltrsrv_eth_set_param(t_ltrd_params param, const void *val, uint32_t size);
extern int ltrsrv_eth_get_param(t_ltrd_params param, void *val, uint32_t* size);
extern int ltrsrv_crate_set_param(t_ltrd_params param, const void *val, uint32_t size);
extern int ltrsrv_crate_get_param(t_ltrd_params param, void *val, uint32_t* size);


int ltrsrv_param_put_uint32(void *val, uint32_t* size, uint32_t set_val) {
    int err = 0;
    if (*size>=sizeof(set_val))  {
        *((uint32_t*)val) = set_val;
        *size = sizeof(set_val);
    } else {
        err = LTRSRV_ERR_INVALID_PARAM_SIZE;
    }
    return err;
}

int ltrsrv_param_get_uint32(const void *val, const uint32_t size, uint32_t *intval) {
    int err = 0;
    if (size != sizeof(*intval)) {
        err = LTRSRV_ERR_INVALID_PARAM_SIZE;
    } else {
        *intval = *((const uint32_t *)val);
    }
    return err;
}

int ltrsrv_set_param(t_ltrd_params param, const void *val, uint32_t size) {
    int err = 0;
    if (LTRD_PARAM_GROUP_IS_ETH(param)) {
        err = ltrsrv_eth_set_param(param, val, size);
    } else if (LTRD_PARAM_GROUP_IS_CRATE(param)) {
        err = ltrsrv_crate_set_param(param, val, size);
    } else {
        err = LTRSRV_ERR_INVALID_PARAM;
    }

    if (err) {
        ltrsrv_log_rec(LTRSRV_LOGLVL_ERR, LTRSRV_LOGSRC_SERVER,err,
                       "Cannot set " LTRD_PROGRAMM_NAME " parameter \'%s\'",
                       ltrsrv_log_get_str(param, f_param_names, sizeof(f_param_names)/sizeof(f_param_names[0])));
    }
    return err;
}

int ltrsrv_get_param(t_ltrd_params param, void *val, uint32_t *size) {
    int err;
    if (LTRD_PARAM_GROUP_IS_ETH(param)) {
        err = ltrsrv_eth_get_param(param, val, size);
    } else if (LTRD_PARAM_GROUP_IS_CRATE(param)) {
        err = ltrsrv_crate_get_param(param, val, size);
    } else {
        err = LTRSRV_ERR_INVALID_PARAM;
    }

    if (err) {
        ltrsrv_log_rec(LTRSRV_LOGLVL_ERR, LTRSRV_LOGSRC_SERVER,err,
                       "Cannot get " LTRD_PROGRAMM_NAME " parameter \'%s\'",
                       ltrsrv_log_get_str(param, f_param_names, sizeof(f_param_names)/sizeof(f_param_names[0])));
    }
    return err;
}
