////////////////////////////////////////////////////////////////////////////////////////
//Document Ready
////////////////////////////////////////////////////////////////////////////////////////
function execDocReady() {
	var pluginGroups = [
		[
			"../reference/lightblue4/docs/lib/widgster/widgster.js",
			"../reference/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
			"../reference/light-blue/lib/vendor/jquery.ui.widget.js"
		],

		[
			"../reference/jquery-plugins/select2-4.0.2/dist/css/select2_lightblue4.css",
			"../reference/jquery-plugins/select2-4.0.2/dist/js/select2.min.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("모든 플러그인 로드 완료");

			// 사이드 메뉴 색상 설정
			$(".widget").widgster();
			setSideMenu("sidebar_menu_security", "sidebar_menu_security_user");

			var resetUserForm = function () {
				$("#select_role").val("").trigger("change");
				$("#select_group").val("").trigger("change");
				$("#user_form").trigger("reset");
				$("#profile_image").empty();
				$("#profile_image").append($("<i />").addClass("fa fa-user").css({ fontSize: "50px", paddingTop: "8px" }));
			};

			$("#user_table")
				.trigger($.Event("init.user_list"))
				.on("select.table", function (event, selectedData) {
					resetUserForm();

					$("#input_username").attr("disabled", true);
					$("#btn_submit").removeClass("btn-primary").addClass("btn-success").text("유저 정보 수정");
					$("#btn_delete").removeClass("hidden");

					$("#select_role_wrapper").removeClass("hidden");
					$("#select_group_wrapper").removeClass("hidden");

					$.when(
						$.ajax({
							url: "/auth-admin/realms/master/user/" + selectedData.id + "/role-mappings/realm",
							success: function (data) {
								$("#select_role")
									.val(
										data.map(function (role) {
											return role.id;
										})
									)
									.trigger("change");
							}
						}),

						$.ajax({
							url: "/auth-admin/realms/master/user/" + selectedData.id + "/groups",
							success: function (data) {
								$("#select_group")
									.val(
										data.map(function (group) {
											return group.id;
										})
									)
									.trigger("change");
							}
						})
					).done(function () {
						$("[data-mh='securityUser']").matchHeight();
					});

					$("#user_form")
						.find("input")
						.each(function () {
							var $self = $(this);
							var key = $self.attr("name");

							$self.val(selectedData[key]);
						});
				})
				.on("deselect.table", function () {
					$("#input_username").attr("disabled", false);
					$("#btn_submit").removeClass("btn-success").addClass("btn-primary").text("신규 유저 생성");
					$("#btn_delete").addClass("hidden");
					$("#select_role_wrapper").addClass("hidden");
					$("#select_group_wrapper").addClass("hidden");

					resetUserForm();

					$("[data-mh='securityUser']").matchHeight();
				})
				.one("draw.dt", function () {
					var params = new URLSearchParams(window.location.search);
					var userId = params.get("userId");

					if (userId) {
						$(this).table().table.rows({ id: userId }).nodes().to$().trigger("click");
					}
				});

			$.ajax({
				url: "/auth-admin/realms/master/roles",
				success: function (data) {
					$("#select_role")
						.select2({
							data: data.map(function (role) {
								return $.extend(role, { id: role.id, text: role.name });
							})
						})
						.on("select2:select", function (event) {
							delete event.params.data.element;

							var selectedData = $("#user_table").table().getSelectedData();
							if (selectedData) {
								$.ajax({
									url: "/auth-admin/realms/master/user/" + selectedData.id + "/role-mappings/realm",
									type: "post",
									contentType: "application/json;charset=utf-8",
									data: JSON.stringify([event.params.data])
								});
							}
						})
						.on("select2:unselect", function (event) {
							delete event.params.data.element;

							var selectedData = $("#user_table").table().getSelectedData();
							if (selectedData) {
								$.ajax({
									url: "/auth-admin/realms/master/user/" + selectedData.id + "/role-mappings/realm",
									type: "delete",
									contentType: "application/json;charset=utf-8",
									data: JSON.stringify([event.params.data])
								});
							}
						});
				}
			});

			$.ajax({
				url: "/auth-admin/realms/master/groups",
				success: function (groups) {
					var getGroups = function (accGroup, group) {
						accGroup.push($.extend(group, { id: group.id, text: group.path.slice(1) }));

						if (group.subGroups.length > 0) {
							group.subGroups.forEach(function (subGroup) {
								getGroups(accGroup, subGroup);
							});
						}

						return accGroup;
					};

					$("#select_group")
						.select2({
							data: groups.reduce(function (accGroup, group) {
								return getGroups(accGroup, group);
							}, [])
						})
						.on("select2:select", function (event) {
							var selectedData = $("#user_table").table().getSelectedData();
							if (selectedData) {
								$.ajax({
									url: "/auth-admin/realms/master/user/" + selectedData.id + "/groups/" + event.params.data.id,
									type: "put"
								});
							}
						})
						.on("select2:unselect", function (event) {
							var selectedData = $("#user_table").table().getSelectedData();
							if (selectedData) {
								$.ajax({
									url: "/auth-admin/realms/master/user/" + selectedData.id + "/groups/" + event.params.data.id,
									type: "delete"
								});
							}
						});
				}
			});

			$("#btn_cancel").on("click", function () {
				resetUserForm();

				var selectedData = $("#user_table").table().getSelectedData();

				if (selectedData) {
					$.ajax({
						url: "/auth-admin/realms/master/user/" + selectedData.id + "/role-mappings/realm",
						success: function (data) {
							$("#select_role")
								.val(
									data.map(function (role) {
										return role.id;
									})
								)
								.trigger("change");
						}
					});

					$("#user_form")
						.find("input")
						.each(function () {
							var $self = $(this);
							var key = $self.attr("name");

							$self.val(selectedData[key]);
						});
				}
			});

			$("#delete_user_modal").on("show.bs.modal", function () {
				var selectedData = $("#user_table").table().getSelectedData();

				$("#deleteUserUsername").text(selectedData.username);
			});

			$("#btn_confirm_delete").on("click", function () {
				var selectedData = $("#user_table").table().getSelectedData();

				$.ajax({
					url: "/auth-admin/realms/master/user/" + selectedData.id,
					type: "delete",
					success: function () {
						$("#delete_user_modal").modal("hide");

						$("#input_username").attr("disabled", false);
						$("#btn_submit").removeClass("btn-success").addClass("btn-primary").text("신규 유저 생성");
						$("#btn_delete").addClass("hidden");
						$("#select_role_wrapper").addClass("hidden");
						$("#select_group_wrapper").addClass("hidden");

						resetUserForm();
						$("#user_table").table().table.ajax.reload();

						jSuccess("유저가 삭제되었습니다.");
					},
					error: function () {
						jError("유저 삭제 중 오류가 발생했습니다.");
					}
				});
			});

			$("#user_form").on("submit", function (event) {
				event.preventDefault();

				var selectedData = $("#user_table").table().getSelectedData();
				var userRepresentation = Object.fromEntries(new FormData(event.target));

				var url = "/auth-admin/realms/master/user";
				var type = "post";
				var success = function () {
					$("#user_table").table().table.ajax.reload();
					jSuccess("유저가 생성되었습니다.");
				};
				var error = function (xhr) {
					jError("유저 생성에 실패했습니다: " + (xhr.responseJSON?.error || "알 수 없는 오류"));
				};

				if (selectedData) {
					url += "/" + selectedData.id;
					type = "put";
					success = function () {
						$("#user_table").table().table.ajax.reload();
						jSuccess("유저 정보가 수정되었습니다.");
					};
					error = function (xhr) {
						jError("유저 정보 수정에 실패했습니다: " + (xhr.responseJSON?.error || "알 수 없는 오류"));
					};
				}

				$.ajax({
					url: url,
					withCredentials: true,
					type: type,
					contentType: "application/json;charset=utf-8",
					data: JSON.stringify(userRepresentation),
					success: success,
					error: error
				});

				return false;
			});

			$("#profile").on("change", function (event) {
				try {
					var reader = new FileReader();
					var file = event.target.files[0];

					if (file) {
						reader.readAsDataURL(file);
						reader.onload = function () {
							var imageUrl =
								typeof reader.result === "string"
									? reader.result
									: String.fromCharCode.apply(null, new Uint16Array(reader.result));

							$("#profile_image").empty();
							$("#profile_image").append(
								$("<img />")
									.attr("src", imageUrl)
									.attr("alt", "Profile Image")
									.css({ width: "100%", height: "100%", objectFit: "cover" })
							);
						};
					}
				} catch (error) {
					console.error(error);
				}
			});

			$("#btn_profile_remove").on("click", function () {
				$("#profile_image").empty();
				$("#profile_image").append($("<i />").addClass("fa fa-user").css({ fontSize: "50px", paddingTop: "8px" }));
			});
		})
		.catch(function (error) {
			console.error("플러그인 로드 중 오류 발생");
			console.error(error);
		});
}

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

	var columnList = [
		{
			name: "firstName",
			title: "FIRST NAME",
			data: "firstName",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "lastName",
			title: "LAST NAME",
			data: "lastName",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "username",
			title: "ID",
			data: "username",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		},
		{
			name: "createdTimestamp",
			title: "Created Date",
			data: "createdTimestamp",
			render: function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			}
		}
	];

	$(document).on("init.user_list", function (event) {
		$(event.target).table({
			columns: columnList,
			dom: "Blfrtip",
			buttons: [
				{
					extend: "excel",
					charset: "UTF-8",
					bom: true,
					className: "btn btn-default btn-sm margin-bottom"
				}
			],
			ajax: {
				url: "/auth-admin/realms/master/users",
				dataSrc: function (json) {
					return json.reduce(function (users, user) {
						return users.concat($.extend(user, { createdTimestamp: new Date(user.createdTimestamp).toLocaleString() }));
					}, []);
				}
			},
			drawCallback: function () {
				$("[data-mh='securityUser']").matchHeight();
			}
		});
	});
})(jQuery);
