////////////////////////////////////////////////////////////////////////////////////////
//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/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"
		],

		[
			"../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/jquery-plugins/jquery-match-height-0.7.2/dist/jquery.matchHeight-min.js",
			"../arms/js/common/table_new.js"
		]

		// 추가적인 플러그인 그룹들을 이곳에 추가하면 됩니다.
	];

	loadPluginGroupsParallelAndSequential(pluginGroups)
		.then(function () {
			console.log("모든 플러그인 로드 완료");

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

			var equals = function (obj1, obj2) {
				var obj1Sort = Object.keys(obj1)
					.sort()
					.reduce(function (obj, key) {
						return (obj[key] = obj1[key]), obj;
					}, {});
				var obj2Sort = Object.keys(obj2)
					.sort()
					.reduce(function (obj, key) {
						return (obj[key] = obj2[key]), obj;
					}, {});

				return Object.entries(obj1Sort).toString() === Object.entries(obj2Sort).toString();
			};

			var render = function (data) {
				return ![null, undefined, ""].includes(data)
					? "<span style='color: #a4c6ff'>" + data + "</span>"
					: "<span style='color: #aaa'>N/A</span>";
			};

			var $targets = [
				{
					table: $("#role_table"),
					cancelBtn: $("#role_btn_cancel"),
					submitBtn: $("#role_btn_submit"),
					nameColumn: {
						name: "name",
						title: "Role Name",
						data: "name",
						render: render
					},
					key: "name",
					getUrl: "/auth-admin/realms/master/roles",
					updateUrl: "/auth-admin/realms/master/role/"
				},
				{
					table: $("#user_table"),
					cancelBtn: $("#user_btn_cancel"),
					submitBtn: $("#user_btn_submit"),
					nameColumn: {
						name: "username",
						title: "User Name",
						data: "username",
						render: render
					},
					key: "id",
					getUrl: "/auth-admin/realms/master/access-control/users",
					updateUrl: "/auth-admin/realms/master/user/"
				},
				{
					table: $("#group_table"),
					cancelBtn: $("#group_btn_cancel"),
					submitBtn: $("#group_btn_submit"),
					nameColumn: {
						name: "path",
						title: "Group Name",
						data: "path",
						render: render
					},
					key: "id",
					getUrl: "/auth-admin/realms/master/access-control/groups",
					updateUrl: "/auth-admin/realms/master/groups/"
				}
			];

			$targets.forEach(function ($target) {
				var $table = $target.table;
				var $cancelBtn = $target.cancelBtn;
				var $submitBtn = $target.submitBtn;

				$table
					.trigger(
						$.Event("init.access_control_list", {
							ajax: {
								url: $target.getUrl,
								dataSrc: function (datas) {
									var attributes = {};
									var result = datas.map(function (data) {
										attributes[data.id] = $.extend({}, data.attributes);

										if (!data.attributes) {
											data.attributes = {};
										}

										return data;
									});

									$table.data("attributes", attributes);

									return result;
								}
							},
							nameColumn: $target.nameColumn
						})
					)
					.on("click", "label.btn", function (event) {
						var $btn = $(event.target).closest(".btn");
						var $row = $btn.closest("tr");
						var key = $btn.find("input[type='checkbox']").attr("name");
						var data = $table.table().getData($row);

						if (data.attributes.hasOwnProperty(key)) {
							delete data.attributes[key];
						} else {
							data.attributes[key] = ["on"];
						}
					});

				$cancelBtn.on("click", function () {
					$table.table().table.ajax.reload();
				});

				$submitBtn.on("click", function () {
					var attributes = $table.data("attributes");

					$table
						.table()
						.getDatas()
						.forEach(function (data) {
							if (!equals(attributes[data.id], data.attributes)) {
								$.ajax({
									url: $target.updateUrl + data[$target.key],
									type: "PUT",
									contentType: "application/json",
									data: JSON.stringify(data)
								});
								attributes[data.id] = $.extend({}, $target.attributes);
								$table.data("attributes", attributes);
							}
						});
				});
			});
		})
		.catch(function (e) {
			console.error("플러그인 로드 중 오류 발생");
			console.error(e);
		});
}

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

	var render = function (data, name, text) {
		return $("<div />", { class: "btn-group", "data-toggle": "buttons", role: "group" })
			.append(
				$("<label />", { class: "btn btn-disabled edit-grey" })
					.append($("<input />", { type: "checkbox", name: name, checked: !!data }))
					.append(text)
					.addClass(data ? "active" : "")
			)
			.prop("outerHTML");
	};

	var columnList = [
		{
			name: "view",
			title: "View",
			data: "attributes.view",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "view", "View");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "dashboard",
			title: "Time, Scope, Resource",
			data: "attributes.dashboard",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "dashboard", "Time, Scope, Resource");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "pdService",
			title: "제품 관리",
			data: "attributes.pdService",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "pdService", "제품 관리");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "pdServiceVersion",
			title: "버전 관리",
			data: "attributes.pdServiceVersion",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "pdServiceVersion", "버전 관리");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reqAdd",
			title: "요구 관리",
			data: "attributes.reqAdd",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reqAdd", "요구 관리");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reqStatus",
			title: "현황 관리 - List",
			data: "attributes.reqStatus",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reqStatus", "현황 관리 - List");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reqStatusCalendar",
			title: "현황 관리 - Calendar",
			data: "attributes.reqStatusCalendar",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reqStatusCalendar", "현황 관리 - Calendar");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reqGantt",
			title: "간트 차트",
			data: "attributes.reqGantt",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reqGantt", "간트 차트");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reqKanban",
			title: "칸반 보드",
			data: "attributes.reqKanban",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reqKanban", "칸반 보드");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "analysisTime",
			title: "일정 분석 <span class='font12'>- Time</span>",
			data: "attributes.analysisTime",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "analysisTime", "일정 분석 <span class='font12'>- Time</span>");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "analysisScope",
			title: "범위 분석 <span class='font12'>- Scope</span>",
			data: "attributes.analysisScope",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "analysisScope", "범위 분석 <span class='font12'>- Scope</span>");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "analysisResource",
			title: '자원 분석 <span class="font12">- Resource</span>',
			data: "attributes.analysisResource",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "analysisResource", '자원 분석 <span class="font12">- Resource</span>');
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "analysisCost",
			title: '비용 분석 <span class="font12">- Cost</span>',
			data: "attributes.analysisCost",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "analysisCost", '비용 분석 <span class="font12">- Cost</span>');
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reportFullData",
			title: "Full Data Report",
			data: "attributes.reportFullData",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "reportFullData", "Full Data Report");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reportSWOT",
			title:
				'SWOT Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>',
			data: "attributes.reportSWOT",
			render: function (data, type) {
				if (type === "display") {
					return render(
						data,
						"reportSWOT",
						'SWOT Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>'
					);
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reportAlmProject",
			title:
				'Project Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>',
			data: "attributes.reportAlmProject",
			render: function (data, type) {
				if (type === "display") {
					return render(
						data,
						"reportAlmProject",
						'Project Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>'
					);
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "reportReqStatus",
			title:
				'Req Status Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>',
			data: "attributes.reportReqStatus",
			render: function (data, type) {
				if (type === "display") {
					return render(
						data,
						"reportReqStatus",
						'Req Status Report <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #b41e27;">Alpha</span>'
					);
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "jiraServer",
			title: "서버 관리",
			data: "attributes.jiraServer",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "jiraServer", "서버 관리");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "mapping",
			title:
				'상태 관리 <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #2477ff;">Beta</span>',
			data: "attributes.mapping",
			render: function (data, type) {
				if (type === "display") {
					return render(
						data,
						"mapping",
						'상태 관리 <span class="label label-danger" style="margin: 0 0 0 1px; line-height: initial; padding: 1px 2px 1px 2px; font-size: 9px; background-color: #2477ff;">Beta</span>'
					);
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "jiraConnection",
			title: "연결 관리",
			data: "attributes.jiraConnection",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "jiraConnection", "연결 관리");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "community_devtools",
			title: "지원 도구",
			data: "attributes.community_devtools",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "community_devtools", "지원 도구");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		},
		{
			name: "mailServer",
			title: "메일 서버",
			data: "attributes.mailServer",
			render: function (data, type) {
				if (type === "display") {
					return render(data, "mailServer", "메일 서버");
				}
				return data;
			},
			className: "dt-body-center",
			defaultContent: "<span style='color: #aaa'>N/A</span>"
		}
	];

	$(document).on("init.access_control_list", function (event) {
		var headerRendered = false;

		$(event.target).table({
			columns: [event.nameColumn].concat(columnList),
			columnDefs: [
				{
					targets: "_all",
					orderable: false,
					searchable: false
				}
			],
			select: false,
			ajax: event.ajax,
			headerCallback: function (tr) {
				if (headerRendered) return;

				var $thead = $(tr).parent();
				var $th = $thead.find("th");
				var $newTh = $th.slice(2).clone();

				var menuList = [
					[
						{ rowspan: 3 },
						{ rowspan: 3 },
						{ html: '<i class="fa fa-mortar-board"></i> Ai' },
						{
							html: '<i class="fa fa-cubes"></i> Product',
							colspan: 2
						},
						{ html: '<i class="fa fa-table"></i> Requirement', colspan: 4 },
						{
							html: '<i class="fa fa-bar-chart-o"></i> Management',
							colspan: 8
						},
						{
							html: '<i class="fa fa-gears" style="margin-top: 3px"></i> System</sup>',
							colspan: 5
						}
					],
					[
						{ html: '<i class="fa fa-mortar-board"></i> Dashboard' },
						{ html: '<i class="fa fa-cubes"></i> Product<sup>service</sup>', colspan: 2 },
						{ html: '<i class="fa fa-table"></i> Req Manage', colspan: 2 },
						{ html: '<i class="fa fa-table"></i> Req Plan', colspan: 2 },
						{ html: '<i class="fa fa-bar-chart-o"></i> Analysis', colspan: 4 },
						{ html: '<i class="fa fa-bar-chart-o"></i> Summary', colspan: 4 },
						{
							html: '<i class="fa fa-gears" style="margin-top: 3px"></i> ALM<sup>jira,gitlab,etc.</sup>',
							colspan: 3
						},
						{
							html: '<i class="fa fa-gears" style="margin-top: 3px"></i> DevOps',
							colspan: 2
						}
					]
				];

				menuList.forEach(function (row, rowIdx) {
					if (rowIdx === 0) {
						var thIdx = 1;

						row.forEach(function (th) {
							$($th[thIdx - 1])
								.attr(th)
								.html(th.html);

							if (th.colspan) {
								var removeStart = thIdx;

								while (thIdx < removeStart + (th.colspan - 1)) {
									$th[thIdx].remove();
									thIdx += 1;
								}
							}

							thIdx++;
						});
						return;
					}

					var $row = $("<tr />", { role: "row" });
					row.forEach(function (th) {
						$row.append($("<th />", th));
					});

					$thead.append($row);
				});

				$thead.append($("<tr />", { role: "row" }).append($newTh));
				headerRendered = true;
			}
		});
	});
})(jQuery);
