// ////////////////////////////////////////////////////////////////////////////////////////
// //Document Ready
// ////////////////////////////////////////////////////////////////////////////////////////
function execDocReady() {
	var pluginGroups = [
		[
			"../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
			"../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select-bluelight.css",
			"../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select.min.js"
		],

		[
			"../reference/lightblue4/docs/lib/widgster/widgster.js",
			"../reference/lightblue4/docs/lib/parsleyjs/dist/parsley.min.js",
			"../reference/lightblue4/docs/lib/parsleyjs/dist/i18n/ko.js"
		],

		[
			"../reference/jquery-plugins/dataTables-1.10.16/media/css/jquery.dataTables_lightblue4.css",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/css/responsive.dataTables_lightblue4.css",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/css/select.dataTables_lightblue4.css",
			"../reference/jquery-plugins/dataTables-1.10.16/media/js/jquery.dataTables.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Responsive/js/dataTables.responsive.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Select/js/dataTables.select.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/RowGroup/js/dataTables.rowsGroup.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/dataTables.buttons.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.html5.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/buttons.print.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/jszip.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/pdfmake.min.js",
			"../reference/jquery-plugins/dataTables-1.10.16/extensions/Buttons/js/vfs_fonts.js"
		],

		["../arms/js/common/table_new.js"]
	];

	loadPluginGroupsParallelAndSequential(pluginGroups)
		.then(function () {
			console.log("모든 플러그인 로드 완료");
			//좌측 메뉴
			setSideMenu("sidebar_menu_security", "sidebar_menu_security_smtp");
			$(".widget").widgster();

			$("#mail_history_table").trigger($.Event("init.mail_history"));

			var accessTokenString;
			(function getAccessToken() {
				$.ajax({
					url: "/auth-admin/token",
					success: function (token) {
						accessTokenString = token.accessTokenString;
					},
					error: function (e) {
						console.error("Error:", e);
					}
				});
			})();

			var smtpProvider = {
				gmail: { server: "smtp.gmail.com", port: "587" },
				office365: { server: "smtp.office365.com", port: "587" },
				naver: { server: "smtp.naver.com", port: "465" },
				daum: { server: "smtp.daum.net", port: "465" }
			};
			$("#smtpProvider").multipleSelect({
				onClick: function (view) {
					var selectedProvider = smtpProvider[view.value];

					if (!smtpProvider.hasOwnProperty(view.value)) {
						selectedProvider = {};
					}

					$("#host").val(selectedProvider.server);
					$("#port").val(selectedProvider.port);
				}
			});

			$("#btn_sync_mail_info").on("click", function () {
				$.ajax({
					url: "/auth-user/api/arms/report/mail-sender/getNodesWithoutRoot.do",
					type: "GET",
					contentType: "application/json",
					success: function (data) {
						console.log("[ mail report :: get sender info ] :: ->", data.result);

						if (data.result.length <= 0) {
							jError("등록된 메일 정보가 없습니다.");
						}
					},
					error: function (e) {
						console.error("Error:", e);
						jError("발신 메일 정보 조회 오류 발생.");
					}
				});
			});

			var realmInfo;
			(function getSMTPConfig() {
				$.ajax({
					url: "/auth-admin/realms/master",
					type: "GET",
					success: function (data) {
						realmInfo = data;

						var serverConfig = data.smtpServer;
						var serverConfigField = Object.keys(serverConfig);

						if (serverConfigField.length > 0) {
							var $smtpForm = $("#smtp_form");

							serverConfigField.forEach(function (field) {
								$smtpForm.find("[name='" + field + "']").val(serverConfig[field]);
							});
						}

						jSuccess("메일 정보 조회에 성공했습니다.");
					},
					error: function (e) {
						console.error("Error:", e);
						jError("메일 정보 조회에 실패했습니다.");
					}
				});
			})();

			$("#btn_test_connection").on("click", function () {
				var smtpConfig = Object.fromEntries(new FormData(document.getElementById("smtp_form")));
				smtpConfig.port = parseInt(smtpConfig.port || 25);
				smtpConfig.from = smtpConfig.user;
				smtpConfig.ssl = true;
				smtpConfig.starttls = false;
				smtpConfig.auth = true;

				$.ajax({
					url: "/auth-admin/realms/master",
					type: "POST",
					contentType: "application/json;charset=utf-8",
					data: JSON.stringify({ smtpServer: smtpConfig }),
					success: function () {
						jSuccess("메일 연동에 성공했습니다.");
					},
					error: function (e) {
						console.error("Error:", e);
						jError("메일 연동 실패, 입력하신 정보를 확인해주세요.");
					}
				});
			});

			$("#smtp_form").on("submit", function (event) {
				var smtpConfig = Object.fromEntries(new FormData(event.target));
				smtpConfig.port = smtpConfig.port || "25";
				smtpConfig.from = smtpConfig.user;
				smtpConfig.ssl = true;
				smtpConfig.starttls = false;
				smtpConfig.auth = true;

				var request = $.extend(true, {}, realmInfo, { smtpServer: smtpConfig });

				delete request.defaultSignatureAlgorithm;
				delete request.oauth2DeviceCodeLifespan;
				delete request.oauth2DevicePollingInterval;
				delete request.passwordCredentialGrantAllowed;
				delete request.privateKey;
				delete request.publicKey;
				delete request.certificate;
				delete request.codeSecret;
				delete request.roles;
				delete request.groups;
				delete request.defaultRole;
				delete request.defaultGroups;
				delete request.passwordPolicy;
				delete request.users;
				delete request.federatedUsers;
				delete request.scopeMappings;
				delete request.clientScopeMappings;
				delete request.clients;
				delete request.clientScopes;
				delete request.defaultDefaultClientScopes;
				delete request.defaultOptionalClientScopes;
				delete request.userFederationProviders;
				delete request.userFederationMappers;
				delete request.eventsExpiration;
				delete request.protocolMappers;
				delete request.components;
				delete request.defaultLocale;
				delete request.authenticationFlows;
				delete request.authenticatorConfig;
				delete request.requiredActions;
				delete request.keycloakVersion;
				delete request.social;
				delete request.updateProfileOnInitialSocialLogin;
				delete request.socialProviders;
				delete request.applicationScopeMappings;
				delete request.applications;
				delete request.oauthClients;
				delete request.clientTemplates;
				delete request.clientProfiles;
				delete request.clientPolicies;

				delete request.webAuthnPolicyAttestationConveyancePreference;
				delete request.webAuthnPolicyAuthenticatorAttachment;
				delete request.webAuthnPolicyRequireResidentKey;
				delete request.webAuthnPolicyUserVerificationRequirement;

				$.ajax({
					url: "/auth-admin/realms/smtp/master",
					type: "POST",
					dataType: "json",
					contentType: "application/json;charset=utf-8",
					data: JSON.stringify(request),
					success: function () {
						jSuccess("메일 정보 저장에 성공했습니다.");
					},
					error: function (e) {
						console.error("Error:", e);
						jError("메일 정보 저장 실패, 입력하신 정보를 확인해주세요.");
					}
				});

				return false;
			});
		})
		.catch(function (e) {
			console.error("플러그인 로드 중 오류 발생");
			console.error(e);
		});
}

+(function ($) {
	"use strict";

	var columnList = [
		{
			name: "sender",
			title: "발신자",
			data: "sender",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "receiver",
			title: "수신자",
			data: "receiver",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "subject",
			title: "제목",
			data: "subject",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "send_date",
			title: "발송일시",
			data: "send_date",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "send_date",
			title: "성공여부",
			data: "send_date",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		}
	];

	$(document).on("init.mail_history", function (event) {
		$(event.target).table({
			columns: columnList,
			data: [],
			dom: "Blfrtip",
			buttons: [
				{
					extend: "excel",
					charset: "UTF-8",
					bom: true,
					className: "btn btn-default btn-sm margin-bottom"
				}
			],
			drawCallback: function () {
				$("[data-mh='mail_setting']").matchHeight();
			}
		});
	});
})(jQuery);
