/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/mg_ol_0028.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0028.pgc - 전문게이트웨이 BCD 인코딩 유틸 서비스 (MG_OL_0028)  [tier=medium]
 *
 * 숫자 문자열(NUM)을 BCD(4bit packed, 2자리/1바이트)로 인코딩한다.
 * 홀수 길이는 하위 니블을 0으로 패딩한다. 인코딩된 패킹길이와 hex 표현을
 * 계산하여 응답한다. (순수 인코딩 로직 - DB 접근 없음)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 17 "app/online/mg_ol_0028.pgc"


#define MG_BCD_MAX  32

/* 숫자문자열 -> BCD packed. 성공 시 패킹 바이트수, 실패 시 -1 */
static int bcd_encode(const char *digits, int ndigit, unsigned char *out, int cap)
{
    int i, packed = (ndigit + 1) / 2;

    if (packed > cap)
        return -1;
    memset(out, 0, packed);
    for (i = 0; i < ndigit; i++) {
        unsigned char nib;
        if (digits[i] < '0' || digits[i] > '9')
            return -1;
        nib = (unsigned char)(digits[i] - '0');
        if ((i & 1) == 0)
            out[i / 2] |= (unsigned char)(nib << 4);   /* 상위 니블 */
        else
            out[i / 2] |= nib;                          /* 하위 니블 */
    }
    return packed;
}

/* packed 바이트열 -> hex 문자열 */
static void bcd_to_hex(const unsigned char *buf, int n, char *hex, int cap)
{
    static const char HX[] = "0123456789ABCDEF";
    int i, j = 0;

    for (i = 0; i < n && j + 2 < cap; i++) {
        hex[j++] = HX[(buf[i] >> 4) & 0x0f];
        hex[j++] = HX[buf[i] & 0x0f];
    }
    hex[j] = '\0';
}

TX_SERVICE(MG_OL_0028, ctx)
{
    char num[MG_BCD_MAX + 1];
    char hex[MG_BCD_MAX * 2 + 1];
    unsigned char packed[MG_BCD_MAX];
    int  ndigit, plen;

    tx_log(TX_LOG_INFO, "[MG_OL_0028] BCD 인코딩 유틸 서비스 진입");

    /* 1) 인코딩 대상 숫자문자열 수신 */
    if (tx_buf_get(ctx->in, "NUM", num, sizeof(num)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0028] 인코딩 대상(NUM) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    ndigit = (int)strlen(num);
    if (ndigit == 0 || ndigit > MG_BCD_MAX * 2) {
        tx_log(TX_LOG_WARN, "[MG_OL_0028] 길이 범위 오류 len=%d", ndigit);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) BCD 인코딩 */
    plen = bcd_encode(num, ndigit, packed, sizeof(packed));
    if (plen < 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0028] 비숫자 포함 인코딩 실패 num=%s", num);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 3) hex 표현 변환 */
    bcd_to_hex(packed, plen, hex, sizeof(hex));

    /* 4) 인코딩 결과 응답 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_setlong(ctx->out, "DIGITS", (long)ndigit);
    tx_buf_setlong(ctx->out, "PACKLEN", (long)plen);
    tx_buf_sets(ctx->out, "BCDHEX", hex);

    /* BCD 인코딩 이력(mg_bcd_log)을 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
             
        
#line 103 "app/online/mg_ol_0028.pgc"
 long h_bcd_digits ;
 
#line 104 "app/online/mg_ol_0028.pgc"
 long h_bcd_packlen ;
 
#line 105 "app/online/mg_ol_0028.pgc"
 char h_bcd_hex [ MG_BCD_MAX * 2 + 1 ] ;
/* exec sql end declare section */
#line 106 "app/online/mg_ol_0028.pgc"


        h_bcd_digits  = (long)ndigit;
        h_bcd_packlen = (long)plen;
        strncpy(h_bcd_hex, hex, sizeof(h_bcd_hex) - 1);
        h_bcd_hex[sizeof(h_bcd_hex) - 1] = '\0';

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_bcd_log ( digit_len , pack_len , bcd_hex ) values ( $1  , $2  , $3  )", 
	ECPGt_long,&(h_bcd_digits),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_bcd_packlen),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_bcd_hex),(long)MG_BCD_MAX * 2 + 1,(long)1,(MG_BCD_MAX * 2 + 1)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 116 "app/online/mg_ol_0028.pgc"

            if (sqlca.sqlcode != TX_SQL_OK) {
                TX_DBIO_LOG_ERR("INSERT mg_bcd_log");
                tx_abort();
            } else {
                tx_commit();
            }
        }
    }

    tx_log(TX_LOG_INFO, "[MG_OL_0028] 인코딩완료 자릿수=%d 패킹=%dbyte hex=%s",
           ndigit, plen, hex);
    tx_return(ctx, TX_OK, ctx->out);
}
