<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
%>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<jsp:include page="/jsp/common/include/css.jsp"/>
<jsp:include page="/jsp/common/include/script.jsp"/>
<script language="javascript">
var url      = '<c:url value="/onl/admin/security/cryptoModuleMan.json" />';
var url_view = '<c:url value="/onl/admin/security/cryptoModuleMan.view" />';
var isDetail = false;

function isValid() {
	if ($('input[name=cryptoName]').val().trim() === '') {
		alert('모듈명을 입력하세요.');
		$('input[name=cryptoName]').focus();
		return false;
	}
	if ($('select[name=algType]').val() === '') {
		alert('알고리즘을 선택하세요.');
		return false;
	}
	if ($('select[name=cipherMode]').val() === '') {
		alert('운영모드를 선택하세요.');
		return false;
	}
	var keySourceType = $('select[name=keySourceType]').val();
	if (keySourceType === '') {
		alert('키 소스 유형을 선택하세요.');
		return false;
	}
	if (keySourceType === 'STATIC') {
		if ($('input[name=encKeyHex]').val().trim() === '') {
			alert('암호화 키(Hex)를 입력하세요.');
			$('input[name=encKeyHex]').focus();
			return false;
		}
	}
	if (keySourceType === 'DYNAMIC') {
		if ($('input[name=keyDerivStrategy]').val().trim() === '') {
			alert('키 도출 전략 FQCN을 입력하세요.');
			$('input[name=keyDerivStrategy]').focus();
			return false;
		}
		if ($('textarea[name=keyDerivParams]').val().trim() === '') {
			alert('키 도출 파라미터(JSON)를 입력하세요.');
			$('textarea[name=keyDerivParams]').focus();
			return false;
		}
	}
	return true;
}

function textToHex(text) {
	if (!text) return '';
	var encoder = new TextEncoder();
	var bytes = encoder.encode(text);
	return Array.from(bytes).map(function(b) {
		return b.toString(16).padStart(2, '0');
	}).join('').toUpperCase();
}

function updateHexFromText(textEl, hexName, lenSpanId) {
	var hex = textToHex($(textEl).val());
	$('input[name=' + hexName + ']').val(hex);
	updateHexLength(hex, lenSpanId);
}

function updateHexLength(hex, lenSpanId) {
	var charLen = hex ? hex.replace(/\s/g, '').length : 0;
	var byteLen = Math.floor(charLen / 2);
	var msg = charLen > 0 ? byteLen + ' bytes (' + charLen + '자)' : '';
	$('#' + lenSpanId).text(msg);
}

function toggleKeySourceFields() {
	var keySourceType = $('select[name=keySourceType]').val();
	if (keySourceType === 'STATIC') {
		$('.static-section').show();
		$('.dynamic-section').hide();
	} else if (keySourceType === 'DYNAMIC') {
		$('.static-section').hide();
		$('.dynamic-section').show();
	} else {
		$('.static-section').show();
		$('.dynamic-section').show();
	}
}

function detail(url, key) {
	if (!isDetail) return;
	$.ajax({
		type: 'POST',
		url: url,
		dataType: 'json',
		data: { cmd: 'DETAIL', cryptoId: key },
		success: function(data) {
			$('input[name=cryptoId]').val(data['CRYPTO_ID']);
			$('input[name=cryptoName]').val(data['CRYPTO_NAME']).attr('readonly', true);
			$('input[name=cryptoDesc]').val(data['CRYPTO_DESC']);
			$('select[name=algType]').val(data['ALG_TYPE']);
			$('select[name=cipherMode]').val(data['CIPHER_MODE']);
			$('select[name=padding]').val(data['PADDING'] || '');
			$('input[name=ivHex]').val(data['IV_HEX']);
			$('select[name=keySourceType]').val(data['KEY_SOURCE_TYPE']);
			$('input[name=encKeyHex]').val(data['ENC_KEY_HEX']);
			$('input[name=decKeyHex]').val(data['DEC_KEY_HEX']);
			$('input[name=keyDerivStrategy]').val(data['KEY_DERIV_STRATEGY']);
			$('textarea[name=keyDerivParams]').val(data['KEY_DERIV_PARAMS']);
			$('select[name=cacheYn]').val(data['CACHE_YN']);
			$('input[name=cacheTtlSec]').val(data['CACHE_TTL_SEC']);
			$('select[name=useYn]').val(data['USE_YN']);
			updateHexLength(data['ENC_KEY_HEX'], 'encKeyLen');
			updateHexLength(data['DEC_KEY_HEX'], 'decKeyLen');
			updateHexLength(data['IV_HEX'], 'ivHexLen');
			if (data['MODIFIED_BY'] || data['MODIFIED_AT']) {
				$('#span_modified_by').text(data['MODIFIED_BY'] || '');
				$('#span_modified_at').text((data['MODIFIED_AT'] || '').replace('T', ' '));
				$('#row_modified_info').show();
			}
			toggleKeySourceFields();
		},
		error: function(e) {
			alert(e.responseText);
		}
	});
}

$(document).ready(function() {
	var returnUrl = getReturnUrlForReturn();
	var key = '${param.cryptoId}';
	if (key !== '' && key !== 'null') {
		isDetail = true;
	}
	detail(url, key);

	$('select[name=keySourceType]').change(function() {
		toggleKeySourceFields();
	});

	$('input[name=encKeyHex]').on('input', function() {
		updateHexLength($(this).val(), 'encKeyLen');
	});
	$('input[name=decKeyHex]').on('input', function() {
		updateHexLength($(this).val(), 'decKeyLen');
	});
	$('input[name=ivHex]').on('input', function() {
		updateHexLength($(this).val(), 'ivHexLen');
	});

	toggleKeySourceFields();

	$('#btn_modify').click(function() {
		if (!isValid()) return;
		var postData = $('#ajaxForm').serializeArray();
		postData.push({ name: 'cmd', value: isDetail ? 'UPDATE' : 'INSERT' });
		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: postData,
			success: function(data) {
				var msg = '<%= localeMessage.getString("common.saveMsg") %>';
				if (data && data.broadcastResult) {
					msg += '\n\n[서버 반영 결과]\n' + data.broadcastResult;
				}
				alert(msg);
				goNav(returnUrl);
			},
			error: function(e) {
				alert(e.responseText);
			}
		});
	});

	$('#btn_delete').click(function() {
		if (confirm('<%= localeMessage.getString("common.confirmMsg") %>') !== true) return;
		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: { cmd: 'DELETE', cryptoId: $('input[name=cryptoId]').val() },
			success: function(data) {
				var msg = '<%= localeMessage.getString("common.deleteMsg") %>';
				if (data && data.broadcastResult) {
					msg += '\n\n[서버 반영 결과]\n' + data.broadcastResult;
				}
				alert(msg);
				goNav(returnUrl);
			},
			error: function(e) {
				alert(e.responseText);
			}
		});
	});

	$('#btn_previous').click(function() {
		goNav(returnUrl);
	});

	buttonControl(isDetail);
	titleControl(isDetail);
});
</script>
</head>
<body>
	<div class="right_box">
		<div class="content_top">
			<ul class="path">
				<li><a href="#">${rmsMenuPath}</a></li>
			</ul>
		</div>
		<div class="content_middle">
			<div class="search_wrap">
				<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> 삭제</button>
				<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> 저장</button>
				<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> 이전</button>
			</div>
			<div class="title">암호화 모듈 설정 상세</div>

			<form id="ajaxForm">
			<input type="hidden" name="cryptoId" />
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:20%;">모듈명 *</th>
					<td><input type="text" name="cryptoName" style="width:300px;" /></td>
				</tr>
				<tr>
					<th>설명</th>
					<td><input type="text" name="cryptoDesc" style="width:400px;" /></td>
				</tr>
				<tr>
					<th>알고리즘 *</th>
					<td>
						<select name="algType">
							<option value="">선택</option>
							<option value="AES">AES</option>
							<option value="ARIA">ARIA</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>운영모드 *</th>
					<td>
						<select name="cipherMode">
							<option value="">선택</option>
							<option value="CBC">CBC</option>
							<option value="GCM">GCM</option>
							<option value="ECB">ECB</option>
							<option value="FF1">FF1</option>
							<option value="FF3-1">FF3-1</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>패딩</th>
					<td>
						<select name="padding">
							<option value="">없음</option>
							<option value="PKCS5Padding">PKCS5Padding</option>
							<option value="NoPadding">NoPadding</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>IV (Hex)</th>
					<td>
						<input type="text" name="ivHex" style="width:380px;" placeholder="HEX 직접 입력" />
						<span id="ivHexLen" style="margin-left:8px; color:#888; font-size:12px;"></span>
						<br/>
						<input type="text" id="ivHexText" style="width:260px; margin-top:4px;" placeholder="텍스트 입력 → HEX 자동 변환"
							oninput="updateHexFromText(this, 'ivHex', 'ivHexLen')" />
						<span class="help-inline">CBC: 16바이트(32자) 필수 / GCM: 설정 시 기본 AAD로 사용</span>
					</td>
				</tr>
				<tr>
					<th>키 소스 유형 *</th>
					<td>
						<select name="keySourceType">
							<option value="">선택</option>
							<option value="STATIC">STATIC</option>
							<option value="DYNAMIC">DYNAMIC</option>
						</select>
					</td>
				</tr>
				<!-- STATIC 전용 -->
				<tr class="static-section">
					<th>암호화 키 (Hex) *</th>
					<td>
						<input type="text" name="encKeyHex" style="width:380px;" placeholder="HEX 직접 입력" />
						<span id="encKeyLen" style="margin-left:8px; color:#888; font-size:12px;"></span>
						<br/>
						<input type="text" id="encKeyText" style="width:260px; margin-top:4px;" placeholder="텍스트 입력 → HEX 자동 변환"
							oninput="updateHexFromText(this, 'encKeyHex', 'encKeyLen')" />
						<span class="help-inline">AES-128: 16bytes(32자) / AES-192: 24bytes(48자) / AES-256: 32bytes(64자)</span>
					</td>
				</tr>
				<tr class="static-section">
					<th>복호화 키 (Hex)</th>
					<td>
						<input type="text" name="decKeyHex" style="width:380px;" placeholder="HEX 직접 입력" />
						<span id="decKeyLen" style="margin-left:8px; color:#888; font-size:12px;"></span>
						<br/>
						<input type="text" id="decKeyText" style="width:260px; margin-top:4px;" placeholder="텍스트 입력 → HEX 자동 변환"
							oninput="updateHexFromText(this, 'decKeyHex', 'decKeyLen')" />
						<span class="help-inline">미입력 시 암호화 키와 동일</span>
					</td>
				</tr>
				<!-- DYNAMIC 전용 -->
				<tr class="dynamic-section">
					<th>키 도출 전략 (FQCN) *</th>
					<td><input type="text" name="keyDerivStrategy" style="width:500px;" /></td>
				</tr>
				<tr class="dynamic-section">
					<th>키 도출 파라미터 (JSON) *</th>
					<td><textarea name="keyDerivParams" style="width:500px; height:80px;"></textarea></td>
				</tr>
				<tr>
					<th>동적 키 캐시 *</th>
					<td>
						<select name="cacheYn">
							<option value="N">N</option>
							<option value="Y">Y</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>캐시 TTL (초)</th>
					<td>
						<input type="number" name="cacheTtlSec" style="width:100px;" />
						<span class="help-inline">기본값 300</span>
					</td>
				</tr>
				<tr>
					<th>사용 여부 *</th>
					<td>
						<select name="useYn">
							<option value="Y">Y</option>
							<option value="N">N</option>
						</select>
					</td>
				</tr>
				<tr id="row_modified_info" style="display:none;">
					<th>수정자 / 수정일시</th>
					<td>
						<span id="span_modified_by" style="font-weight:bold;"></span>
						<span style="margin:0 8px; color:#ccc;">|</span>
						<span id="span_modified_at" style="color:#555;"></span>
					</td>
				</tr>
			</table>
			</form>
		</div>
	</div>
</body>
</html>
