var publicHolidaysTable;

function execDocReady() {
	var pluginGroups = [
		[
			"../reference/light-blue/lib/vendor/jquery.ui.widget.js",
			"../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Templates_js_tmpl.js",
			"../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Load-Image_js_load-image.js",
			"../reference/light-blue/lib/vendor/http_blueimp.github.io_JavaScript-Canvas-to-Blob_js_canvas-to-blob.js",
			"../reference/light-blue/lib/jquery.iframe-transport.js",
			"../reference/light-blue/lib/jquery.fileupload.js",
			"../reference/light-blue/lib/jquery.fileupload-fp.js",
			"../reference/light-blue/lib/jquery.fileupload-ui.js"
		],
		[
			"../reference/jquery-plugins/select2-4.0.2/dist/css/select2_lightblue4.css",
			"../reference/jquery-plugins/lou-multi-select-0.9.12/css/multiselect-lightblue4.css",
			"../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select-bluelight.css",
			"../reference/jquery-plugins/select2-4.0.2/dist/js/select2.min.js",
			"../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.quicksearch.js",
			"../reference/jquery-plugins/lou-multi-select-0.9.12/js/jquery.multi-select.js",
			"../reference/jquery-plugins/multiple-select-1.5.2/dist/multiple-select.min.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/lightblue4/docs/lib/slimScroll/jquery.slimscroll.min.js",
			"../reference/jquery-plugins/unityping-0.1.0/dist/jquery.unityping.min.js",
			"../reference/lightblue4/docs/lib/widgster/widgster.js"
		],
		[
		   "../reference/jquery-plugins/fullcalendar-6.1.15/dist/index.global.js",
		   "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.min.css",
           "../reference/light-blue/lib/bootstrap-datepicker.js",
           "../reference/jquery-plugins/datetimepicker-2.5.20/build/jquery.datetimepicker.full.min.js"
		]
		// 추가적인 플러그인 그룹들을 이곳에 추가하면 됩니다.
	];

	loadPluginGroupsParallelAndSequential(pluginGroups)
		.then(function () {
			console.log("모든 플러그인 로드 완료");
			//상단 메뉴
			$(".widget").widgster();
			setSideMenu("sidebar_menu_system", "sidebar_menu_system_backup_restore");

            getHolidayList();
            drawPublicHolidaysTable();
            controlToggleButton();
            updateToggleButton();
		})
		.catch(function (e) {
			console.error("플러그인 로드 중 오류 발생");
		});
}
function getHolidayList() {
    $.ajax({
        url: '/auth-user/api/arms/backoffice/holiday/getNodesWithoutRoot.do',
        type: 'GET',
        contentType: 'application/json',
        statusCode: {
            200: function (data) {
                console.log("[ Time off :: get holiday list ] :: ->");
                console.log(data.result);
                renderCalendar(data.result);
            }
        },
        error: function(e) {
            console.error('Error:', e);
            jError("정보 조회 오류 발생.");
        }
    });
}

function renderCalendar(holidayList) {

    const publicHolidays = holidayList.filter(item => !('c_user_id' in item));
    const userHolidays = holidayList.filter(item => 'c_user_id' in item);

    // 공휴일
    const publicHolidayEvents = $.map(publicHolidays, function (item) {
        return {
            start: formatDate(item.c_holiday_date),
            end: formatDate(item.c_holiday_date),
            editable: false,
            title: item.c_desc,
            color: '#F4511E',
            allDay: true
        };
    });

    // 사용자 휴일
    const userHolidayEvents = $.map(userHolidays, function (item) {
        return {
            title: item.c_desc,
            start: formatDate(item.c_holiday_date),
            allDay: true
        };
    });

    const events = publicHolidayEvents.concat(userHolidayEvents);

    if (window.calendar && typeof window.calendar.destroy === 'function') {
      window.calendar.destroy();
    }

    var calendarEl = document.getElementById('calendar');

    window.calendar = new FullCalendar.Calendar(calendarEl, {
        headerToolbar: {
        				left: "prevYear,prev,next,nextYear today",
        				center: "title",
        				right: "multiMonthYear,dayGridMonth,dayGridWeek,dayGridDay"
        			},
        views:{
            dayGridMonth:{
                titleFormat: { year: 'numeric', month: '2-digit' }
            }
        },
        buttonText: {
            year:'년',
            today: '오늘',
            month: '월',
            week: '주',
            day: '일',
            list: '목록'
        },
        initialDate: new Date(),
        navLinks: true, // can click day/week names to navigate views
        businessHours: true, // display business hours
        editable: true,
        selectable: true,
        events: events,
        dayMaxEvents: true,
        datesSet: function (info) {
                updateYearMonthLabels();
        },
        dateClick: function(info) {
            console.log("Clicked date: " + info.dateStr);
            $('#selectedDate').val(info.dateStr);
            $('#registerHolidayModal').data('clicked-date', info.dateStr);
            $('#registerHolidayModal').modal('show');
        }
    });
    window.calendar.render();
}
function formatDate(date) {
    const formatter = new Intl.DateTimeFormat('ko-CA', {
        timeZone: 'Asia/Seoul',
        year:  'numeric',
        month: '2-digit',
        day:   '2-digit'
    });

    const parts = formatter.formatToParts(date);
    const year  = parts.find(p => p.type === 'year').value;
    const month = parts.find(p => p.type === 'month').value;
    const day   = parts.find(p => p.type === 'day').value;

  return `${year}-${month}-${day}`;
}


function drawPublicHolidaysTable() {

	var columnList = [
		{
			name: "c_desc",
			title: "구분",
			data: "c_desc",
			render: function (data, type, row, meta) {
				return data;
			},
			className: "dt-body-left",
			visible: true
		},
		{
			name: "c_holiday_date",
			title: "일자",
			data: "c_holiday_date",
			render: function (data, type, row, meta) {
				return formatDate(data);
			},
			className: "dt-body-left",
			visible: true
		}
	];
	var rowsGroupList = [];
	var columnDefList = [];
	var orderList = [];
	var jquerySelector = "#publicHolidaysTable";
	var ajaxUrl = "";
	var jsonRoot = "result";
	var buttonList = [];
	var selectList = {};
	var isServerSide = false;
	var isAjax = true;

	var ajaxUrl = "/auth-user/api/arms/backoffice/holiday/getNodesWithoutRoot.do";

	publicHolidaysTable = dataTable_build(
		jquerySelector,
		ajaxUrl,
		jsonRoot,
		columnList,
		rowsGroupList,
		columnDefList,
		selectList,
		orderList,
		buttonList,
		isServerSide,
		400,
		null,
		isAjax
	);
	publicHolidaysTable.columns.adjust();
}
function dataTableClick(tempDataTable, selectedData) {
}

function dataTableCallBack(settings, json) {
}

function dataTableDrawCallback(tableInfo) {
	$("#" + tableInfo.sInstance)
		.DataTable()
		.columns.adjust()
		.responsive.recalc();
}

function controlToggleButton(){
$('input[name="holidayType"]').change(function () {
    if ($(this).val() === 'public') {
      $('#publicHolidaySection').show();
      $('#userHolidaySection').hide();
    } else {
      $('#publicHolidaySection').hide();
      $('#userHolidaySection').show();
    }
  });
}

function updateToggleButton(){
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');

    $('#yearLabel').text(year);
    $('#monthLabel').text(month);
}
function updateYearMonthLabels() {
    const currentDate = window.calendar.getDate(); // FullCalendar가 보고 있는 중심 날짜
    const d = new Date(currentDate);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');

    $('#yearLabel').text(year);
    $('#monthLabel').text(month);
}
