(function ($) {
	'use strict';

	var scheduleConfig = {};

	var monthInput = $('#month');
	var dateInput = $('#date');
	var datePeriodUtil = $('#date_period_util');
	var datePeriod = $('#date_period');
	var timePeriod = $('#time_period');
	var scheduleStartTime = $('#schedule_start_time');

	var popupCronExpression = $('#popup_cron_expression');
	var popupExpression = $('#popup_expression');

	var cronArr = ['0', '*', '*', '*', '*', '*'];

	var minute = 1;
	var hour = 2;
	var date = 3;
	var month = 4;
	var week = 5;

	monthInput.on('change', function (event) {
		var value = event.target.value ? Math.min(Math.max(parseInt(event.target.value), 1), 12) : '*';
		cronArr[month] = value;

		var cronExpression = cronArr.join(' ');
		popupCronExpression.val(cronExpression);
		popupExpression.val(cronstrue.toString(cronExpression, { locale: 'ko', use24HourTimeFormat: true }));
	});

	dateInput.on('change', function (event) {
		var value = event.target.value ? Math.min(Math.max(parseInt(event.target.value), 1), 31) : '*';
		cronArr[date] = value;

		var cronExpression = cronArr.join(' ');
		popupCronExpression.val(cronExpression);
		popupExpression.val(cronstrue.toString(cronExpression, { locale: 'ko', use24HourTimeFormat: true }));
	});

	datePeriodUtil.on('select2:select', function (event) {
		var value = event.params.data.id.split(',');
		datePeriod.val(value).change();
	});

	datePeriod.on('change', function (event) {
		var selectedData = $(event.target).select2('data');
		var value = $.map(selectedData, function (data) {
			return data.id;
		});

		if (value) {
			cronArr[week] = value.join(',');
			datePeriodUtil.val(cronArr[week]).trigger('change');
		} else {
			cronArr[week] = '*';
		}

		var cronExpression = cronArr.join(' ');
		popupCronExpression.val(cronExpression);
		popupExpression.val(cronstrue.toString(cronExpression, { locale: 'ko', use24HourTimeFormat: true }));
	});

	timePeriod.on('select2:select', function (event) {
		var value = event.params.data.id;
		var startHour = scheduleStartTime.val() ? scheduleStartTime.val().split(':')[0] : '*';

		cronArr[hour] = value ? value.replace(/\*/, startHour) : startHour;

		var cronExpression = cronArr.join(' ');
		popupCronExpression.val(cronExpression);
		popupExpression.val(cronstrue.toString(cronExpression, { locale: 'ko', use24HourTimeFormat: true }));
	});

	scheduleStartTime.on('change', function (event) {
		if (!event.target.value) {
			cronArr[hour] = timePeriod.val() ? timePeriod.val().replace(/.+(?=\/)/, '*') : '*';
			cronArr[minute] = '*';
		} else {
			var value = event.target.value ? event.target.value.split(':') : ['*', '*'];
			var startHour = value[0];
			var startMinute = value[1];

			cronArr[hour] = timePeriod.val() ? timePeriod.val().replace(/\*/, startHour) : parseInt(startHour);
			cronArr[minute] = parseInt(startMinute);
		}

		var cronExpression = cronArr.join(' ');
		popupCronExpression.val(cronExpression);
		popupExpression.val(cronstrue.toString(cronExpression, { locale: 'ko', use24HourTimeFormat: true }));
	});

	$('#save_schedule_btn').on('click', function () {
		var name = $('#schedule_name').val();

		if (!name) return;

		if (scheduleConfig) {
			$.ScheduleConfigApi.updateSchedule()({
				type: 'put',
				data: JSON.stringify({
					c_id: scheduleConfig.c_id,
					job_name: name,
					cron_exp: popupCronExpression.val(),
				}),
				success: function () {
					$('#schedule_list_table').trigger($.Event('init.schedule_list'));
				},
			});
		} else {
			$.ScheduleConfigApi.addSchedule()({
				type: 'post',
				data: JSON.stringify({
					c_type: 'folder',
					c_title: name,
					ref: 2,
					job_name: name,
					cron_exp: popupCronExpression.val(),
				}),
				success: function () {
					$('#schedule_list_table').trigger($.Event('init.schedule_list'));
				},
				error: function (e) {
					jError('스케줄 생성에 실패했습니다.');
				},
			});
		}
	});

	$('#schedule_control_modal')
		.on('shown.bs.modal', function (event) {
			var $modalTriggerBtn = $(event.relatedTarget);
			scheduleConfig = $modalTriggerBtn.data('row');

			if (!scheduleConfig) return;

			$('#schedule_name').val(scheduleConfig.job_name);

			$('#sender-scheduler-info').text(scheduleConfig.job_name);
			$('#sender-scheduler-info').css('color', '#a4c6ff');
			$('#scheduler_util .chat-message-body').css('border-left', '2px solid #e5603b');
			$('#scheduler_util #scheduler-arrow').css('border-right', '5px solid #e5603b');

			var cronExp = scheduleConfig.cron_exp;

			if (cronExp) {
				var schedule = cronExp.split(' ');

				datePeriodUtil.val(schedule[week]).trigger('change');
				datePeriod.val(schedule[week].split(',')).trigger('change');

				monthInput.val(schedule[month]).trigger('change');
				dateInput.val(schedule[date]).trigger('change');

				if (/[0-9]+(?=\/)/.test(schedule[hour])) {
					$('#same_day_repeat').iCheck('check');
					timePeriod.val(schedule[hour].replace(/[0-9]+(?=\/)/, '*')).trigger('change');
				}

				if (schedule[hour] !== '*') {
					scheduleStartTime
						.val(('0' + schedule[hour].replace(/\/[0-9]/, '')).slice(-2) + ':' + ('0' + schedule[minute]).slice(-2))
						.trigger('change');
				} else {
					scheduleStartTime.val('').trigger('change');
				}

				popupCronExpression.val(cronExp);
			}
		})
		.on('hidden.bs.modal', function () {
			$('#schedule_name').val('');

			$('#sender-scheduler-info').text('선택되지 않음');
			$('#sender-scheduler-info').css('color', '#f8f8f8');
			$('#scheduler_util .chat-message-body').css('border-left', '2px solid #a4c6ff');
			$('#scheduler_util #scheduler-arrow').css('border-right', '5px solid #a4c6ff');

			$('.iCheck').iCheck('uncheck');
			monthInput.val('').trigger('change');
			dateInput.val('').trigger('change');
			datePeriodUtil.val('').trigger('change');
			datePeriod.val('').trigger('change');
			timePeriod.val('').trigger('change');
			scheduleStartTime.val('').trigger('change');
			$('#schedule_last_time').val('');
			popupExpression.val('');
			popupCronExpression.val('');
		});
})(jQuery);
