<%@ 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"/>
	<link href="<c:url value="/addon/bootstrap-icons-1.11.3/bootstrap-icons.min.css"/>" rel="stylesheet" />

	<script language="javascript" >
		var url      ='<c:url value="/onl/admin/httpouttlsinfo/httpOutTlsInfoMan.json" />';
		var url_view ='<c:url value="/onl/admin/httpouttlsinfo/httpOutTlsInfoMan.view" />';
		var isDetail = false;

		function init() {
			$.ajax({
				type : "POST",
				url:url,
				dataType:"json",
				data:{cmd: 'LIST_INIT_COMBO'},
				success:function(json){
					new makeOptions("CODE","NAME").setObj($("select[name=clientId]"))
						.setData(json.clientIdRows).setFormat(codeName3OptionFormat).rendering();

					var key = "${param.clientId}";
					if (key != "" && key != "null") {
						detail(key);
					}
				},
				error: function (e) {
					alert("Client 목록을 불러오는데 실패했습니다.");
				}
			});
		}

		function toBase64(file) {
			return new Promise((resolve, reject) => {
				const reader = new FileReader();
				reader.readAsArrayBuffer(file);
				reader.onload = () => {
					const bytes = new Uint8Array(reader.result);
					const base64 = btoa(String.fromCharCode.apply(null, bytes));
					resolve(base64);
				};
				reader.onerror = error => reject(error);
			});
		}


		function detail(key) {
			if (!isDetail) return;

			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'DETAIL', clientId: key},
				success: function (json) {
					var data = json;

					$("#clientId").val(data.clientId).prop('disabled', true);

					$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function () {
						var name = $(this).attr("name");
						var tag = $(this).prop("tagName").toLowerCase();
						$(tag + "[name=" + name + "]").val(data[name]);
					});

					// 파일명 표시
					if (data.keystoreFilename) {
						$('input[name="keystoreFilename"]').val(data.keystoreFilename).show();
						$("#deleteKeystoreBtn").show();
					}
					if (data.truststoreFilename) {
						$('input[name="truststoreFilename"]').val(data.truststoreFilename).show();
						$("#deleteTruststoreBtn").show();
					}
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		/*비밀번호*/
		function togglePassword(inputId, toggleId) {
			const inputType = $(inputId).attr("type");
			if(inputType == 'password'){
				$(inputId).attr("type", "text");
				$(toggleId).find('i').removeClass('bi-eye').addClass('bi-eye-slash');
			} else {
				$(inputId).attr("type", "password");
				$(toggleId).find('i').removeClass('bi-eye-slash').addClass('bi-eye');
			}
		}

		function updateFileInfo(inputElement, filenameElement, deleteButton) {
			var fileName = inputElement.files[0] ? inputElement.files[0].name : '';
			if (fileName) {
				$(filenameElement).val(fileName).show();
				$(deleteButton).show();
			} else {
				$(filenameElement).val('').hide();
				$(deleteButton).hide();
			}
		}

		function deleteFile(fileType) {
			if (confirm(fileType + " 파일을 삭제하시겠습니까?")) {
				if (fileType === 'keystore') {
					$('input[name="keystoreFile"]').val('');
					$('input[name="keystoreFilename"]').val('');
					$('input[name="keystorePassword"]').val('');
					$("#deleteKeystoreBtn").hide();
				} else if (fileType === 'truststore') {
					$('input[name="truststoreFile"]').val('');
					$('input[name="truststoreFilename"]').val('');
					$('input[name="truststorePassword"]').val('');
					$("#deleteTruststoreBtn").hide();
				}
			}
		}

		$(document).ready(function () {
			var returnUrl = getReturnUrlForReturn();
			var key = "${param.clientId}";
			if (key != "" && key != "null") {
				isDetail = true;
			}

			$('input[name="keystoreFile"]').change(function() {
				updateFileInfo(this, 'input[name="keystoreFilename"]', '#deleteKeystoreBtn');
			});

			$('input[name="truststoreFile"]').change(function() {
				updateFileInfo(this, 'input[name="truststoreFilename"]', '#deleteTruststoreBtn');
			});

			if (isDetail) {
				var keystoreFilename = $('input[name="keystoreFilename"]').val();
				var truststoreFilename = $('input[name="truststoreFilename"]').val();

				$("#title").append(" 수정");
				buttonControl(true);
				if (keystoreFilename) {
					$('#keystoreFileName').text(keystoreFilename).show();
					$("#deleteKeystoreBtn").show();
				}
				if (truststoreFilename) {
					$('#truststoreFileName').text(truststoreFilename).show();
					$("#deleteTruststoreBtn").show();
				}
			} else {
				$("#title").append(" 등록");
				$("#btn_modify").html('<i class="material-icons">save</i> <%= localeMessage.getString("button.register") %>');
				buttonControl(false);
			}


			init();

			$('#toggleKeystorePassword').click(function () {
				togglePassword("#keystorePassword", "#toggleKeystorePassword");
			});

			$('#toggleTruststorePassword').click(function () {
				togglePassword("#truststorePassword", "#toggleTruststorePassword");
			});


			$("#btn_modify").click(async function () {
				if (!checkRequired("ajaxForm"))	return;

				var $clientId = $('#clientId');
				var wasDisabled = $clientId.prop('disabled');
				$clientId.prop('disabled', false);

				var postData = $('#ajaxForm').serializeArray();

				if (wasDisabled) {
					$clientId.prop('disabled', true);
				}

				if (isDetail) {
					postData.push({name: "cmd", value: "UPDATE"});
				} else {
					postData.push({name: "cmd", value: "INSERT"});
				}

				// 파일 처리
				const keystoreFile = $('input[name="keystoreFile"]')[0].files[0];
				const truststoreFile = $('input[name="truststoreFile"]')[0].files[0];

				if (keystoreFile) {
					const keystoreBase64 = await toBase64(keystoreFile);
					postData.push({name: "keystoreInfo", value: keystoreBase64});
				}

				if (truststoreFile) {
					const truststoreBase64 = await toBase64(truststoreFile);
					postData.push({name: "truststoreInfo", value: truststoreBase64});
				}

				$.ajax({
					type: "POST",
					url: url,
					data: postData,
					success: function (args) {
						alert("<%= localeMessage.getString("common.saveMsg") %>");
						goNav(returnUrl); //LIST로 이동
					},
					error: function (e) {
						alert(e.responseText);
					}
				});
			});

			$("#btn_delete").click(function () {
				if (confirm("<%= localeMessage.getString("common.confirmMsg")%>") != true)
					return;
							
				var $clientId = $('#clientId');				
				$clientId.prop('disabled', false);
			
				var postData = $('#ajaxForm').serializeArray();
				$clientId.prop('disabled', true);

				postData.push({name: "cmd", value: "DELETE"});

				$.ajax({
					type: "POST",
					url: url,
					data: postData,
					success: function (args) {
						alert("<%= localeMessage.getString("common.deleteMsg") %>");
						goNav(returnUrl); //LIST로 이동
					},
					error: function (e) {
						alert(e.responseText);
					}
				});
			});

			$("#btn_previous").click(function () {
				goNav(returnUrl); //LIST로 이동
			});

			titleControl(isDetail);

		});
	</script>
</head>
<body>
<div class="right_box">
	<div class="content_top">
		<ul class="path">
			<li><a href="#">${rmsMenuPath}</a></li>
		</ul>
	</div><!-- end content_top -->
	<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> <%= localeMessage.getString("button.delete") %></button>
			<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
			<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
		</div>
		<div class="title">HTTP Client mTLS 정보<span class="tooltip">Manage HTTP Client mTLS Information</span></div>

		<!-- detail -->
		<form id="ajaxForm">
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:15%;">Client 아이디 <span style="color:red">*</span></th>
					<td>
						<div class="select-style">
							<select name="clientId" id="clientId" data-required data-warning="Client 아이디를 입력하여 주십시오." >
								<option value="">선택</option>
							</select>
						</div>
					</td>
				</tr>
				<tr>
					<th>Store Type <span style="color:red">*</span></th>
					<td>
						<div class="select-style">
							<select name="storeType" data-required data-warning="Store Type을 선택하여 주십시오.">
								<option value="">선택</option>
								<option value="JKS">JKS</option>
								<option value="PKCS12">PKCS12</option>
							</select>
						</div>
					</td>
				</tr>
				<tr>
					<th>Keystore 파일</th>
					<td>
						<input type="text" name="keystoreFilename" style="display:inline-block; width:30%;" data-required data-warning="Keystore 파일을 등록하여 주십시오." readonly />
						<input type="file" name="keystoreFile" accept=".jks,.p12,.pfx" style="display:none;" />
						<button type="button" class="cssbtn smallBtn" onclick="$('input[name=keystoreFile]').click()">파일 선택</button>
						<button type="button" class="cssbtn smallBtn" id="deleteKeystoreBtn" onclick="deleteFile('keystore')" style="display:none;">
							<i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
						</button>
					</td>
				</tr>
				<tr>
					<th >Keystore 비밀번호 <span style="color:red">*</span></th>
					<td>
						<div class="input-group">
							<input type="password" name="keystorePassword" id="keystorePassword" data-required data-warning="Keystore 비밀번호를 입력하여 주십시오." style="width: calc(100% - 20px);" autocomplete="new-password"/>
							<span class="input-group-text" style="cursor: pointer;" id="toggleKeystorePassword">
								<i class="bi bi-eye"></i>
							</span>
						</div>
					</td>
				</tr>
				<tr>
					<th>Truststore 파일</th>
					<td>
						<input type="text" name="truststoreFilename" style="display:inline-block; width:30%;" readonly  />
						<input type="file" name="truststoreFile" accept=".jks,.p12,.pfx" style="display:none;" />
						<button type="button" class="cssbtn smallBtn" onclick="$('input[name=truststoreFile]').click()">파일 선택</button>
						<button type="button" class="cssbtn smallBtn" id="deleteTruststoreBtn" onclick="deleteFile('truststore')" style="display:none;">
							<i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
						</button>
					</td>

				</tr>
				<tr>
					<th>Truststore 비밀번호</th>
					<td>
						<div class="input-group">
							<input type="password" name="truststorePassword" id="truststorePassword" style="width: calc(100% - 20px);" autocomplete="new-password"/>
							<span class="input-group-text" style="cursor: pointer;" id="toggleTruststorePassword">
								<i class="bi bi-eye"></i>
							</span>
						</div>
					</td>
				</tr>
			</table>
		</form>

	</div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>

