@using GreenTree.Nachtragsmanagement.Web.Extensions
@using GreenTree.Nachtragsmanagement.Core.Plugins

@{ 
	var userContext = GreenTree.Nachtragsmanagement.Core.CommonHelper.UserContext();
}

@model GreenTree.Nachtragsmanagement.Web.Models.Misc.MailNotificationDataModel

<div class="mailNotificationEditContainer">

	<script src="~/Scripts/jquery-cron-min.js"></script>
	<script>
		var textSeparator = ", ";
		var pluginSystemName = "@Model.NotificationPluginSystemName";
		var cronEditor = null;
		var notificationPluginDictionary = {};
		var notificationJobDictionary = {};

		@foreach (var notificationPlugin in (IEnumerable<INotificationPlugin>)ViewData["AllNotificationPlugins"])
		{
			ViewContext.Writer.WriteLine("notificationPluginDictionary[\"" + notificationPlugin.SystemName + "\"] = \"" + notificationPlugin.Description + "\";");

			foreach (var notificationJob in notificationPlugin.AvailableNotificationJobs)
			{
				ViewContext.Writer.WriteLine("notificationJobDictionary[\"" + notificationJob.SystemName + "\"] = \"" + notificationJob.Description + "\";");
			}
		}

		//cronEditor = $("#cronExpressionEditor").cron({
		//	onChange: function () {
		//		$("#CronExpression").val($(this).cron("value"));
		//		$("#cronExpressionDisplay").text($(this).cron("value"));
		//	}
		//});

		function changeElementText(selector, textArray) {
			for (var i = 0; i < textArray.length; i++) {
				$(selector).contents().filter(function () {
					return this.nodeType == 3;
				})[i].nodeValue = textArray[i];
			}
		}

		@*$(document).ready(function () {
			@if (String.IsNullOrEmpty(Model.CronExpression))
			{
				ViewContext.Writer.WriteLine("cronEditor.cron('value', '0 6 * * 1');");
			}
			else
			{
				ViewContext.Writer.WriteLine("cronEditor.cron('value', '" + Model.CronExpression + "');");
			}
			changeElementText(".cron-period", ["Jede(r/s) "]);
			changeElementText(".cron-block-mins", ["auf der ", " Minute nach der Stunde"]);
			changeElementText(".cron-block-time", ["um "]);
			changeElementText(".cron-block-dow", ["am "]);
			changeElementText(".cron-block-dom", ["am "]);
			changeElementText(".cron-block-month", [" des "]);
			$('select[name="cron-period"] > option[value="minute"]').text("Minute");
			$('select[name="cron-period"] > option[value="hour"]').text("Stunde");
			$('select[name="cron-period"] > option[value="day"]').text("Tag");
			$('select[name="cron-period"] > option[value="week"]').text("Woche");
			$('select[name="cron-period"] > option[value="month"]').text("Monat");
			$('select[name="cron-period"] > option[value="year"]').text("Jahr");
			$('select[name="cron-dow"] > option[value="0"]').text("Sonntag");
			$('select[name="cron-dow"] > option[value="1"]').text("Montag");
			$('select[name="cron-dow"] > option[value="2"]').text("Dienstag");
			$('select[name="cron-dow"] > option[value="3"]').text("Mittwoch");
			$('select[name="cron-dow"] > option[value="4"]').text("Donnerstag");
			$('select[name="cron-dow"] > option[value="5"]').text("Freitag");
			$('select[name="cron-dow"] > option[value="6"]').text("Samstag");
			$('select[name="cron-month"] > option[value="1"]').text("Januar");
			$('select[name="cron-month"] > option[value="2"]').text("Februar");
			$('select[name="cron-month"] > option[value="3"]').text("März");
			$('select[name="cron-month"] > option[value="4"]').text("April");
			$('select[name="cron-month"] > option[value="5"]').text("Mai");
			$('select[name="cron-month"] > option[value="6"]').text("Juni");
			$('select[name="cron-month"] > option[value="7"]').text("Juli");
			$('select[name="cron-month"] > option[value="8"]').text("August");
			$('select[name="cron-month"] > option[value="9"]').text("September");
			$('select[name="cron-month"] > option[value="10"]').text("Oktober");
			$('select[name="cron-month"] > option[value="11"]').text("November");
			$('select[name="cron-month"] > option[value="12"]').text("Dezember");
			for (var i = 1; i <= 31; i++) {
				$('select[name="cron-dom"] > option[value="' + i + '"]').text(i + ".");
			}
		});*@

		function saveMailNotification() {
			$("#CronExpression").val(generateCronExpression("devRecurrenceFormCron"));
			var form = $("#mailNotificationEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditMailNotification", "Misc")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".mailNotificationEditContainer").remove();
							if (response == "success") {
								devGridViewMailNotifications.PerformCallback();
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function onListBoxSelectionChanged(s, e) {
			updateText();
		}

		function updateText() {
			var selectedItems = UserValues.GetSelectedItems();
			devDropDownListUserValues.SetText(getSelectedItemsText(selectedItems));
		}

		function synchronizeListBoxValues(s, e) {
			UserValues.UnselectAll();
			var texts = s.GetText().split(textSeparator);
			var values = getValuesByTexts(texts);
			UserValues.SelectValues(values);
			updateText();
		}

		function getSelectedItemsText(items) {
			var texts = [];
			for (var i = 0; i < items.length; i++)
				texts.push(items[i].text);
			return texts.join(textSeparator);
		}

		function getValuesByTexts(texts) {
			var actualValues = [];
			var item;
			for (var i = 0; i < texts.length; i++) {
				item = UserValues.FindItemByText(texts[i]);
				if (item != null)
					actualValues.push(item.value);
			}
			return actualValues;
		}

		function onNotificationPluginSelectedIndexChanged() {
			pluginSystemName = NotificationPluginSystemName.GetValue();
			NotificationJobSystemName.PerformCallback();
			$("#notificationPluginDescription").text(notificationPluginDictionary[pluginSystemName]);
		}

		function onNotificationJobSelectedIndexChanged() {
			var jobSystemName = NotificationJobSystemName.GetValue();
			$("#notificationJobDescription").text(notificationJobDictionary[jobSystemName]);
		}
	</script>

	<style>
		.notificationDescription {
			margin-top: 8px;
			color: #009688;
			font-style: italic;
		}

		#cronExpressionEditor {
			margin-top: 3px;
			padding-top: 10px;
			border-top: 1px solid #009688;
		}

		#cronExpressionEditor select {
			padding: 6px 4px;
			border: 1px solid #DCDCDC;
			border-radius: 2px;
			-webkit-border-radius: 2px;
			-moz-border-radius: 2px;
			-o-border-radius: 2px;
			-khtml-border-radius: 2px;
		}

		#cronExpressionEditor select:focus {
			border: 1px solid #009688;
		}
	</style>

	@Html.DevExpress().PopupControl(s =>
{
	s.Name = "devPopupControlEditMailNotification";

	if (Model.Id == -1)
		s.HeaderText = "Neue Benachrichtigung erstellen";
	else
		s.HeaderText = "\"" + Model.NotificationPluginSystemNameDescription + "\" bearbeiten";

	s.Modal = true;
	s.Width = new Unit(800, UnitType.Pixel);
	s.CloseAction = CloseAction.CloseButton;
	s.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
	s.PopupVerticalAlign = PopupVerticalAlign.TopSides;
	s.PopupVerticalOffset = 10;
	s.AllowDragging = true;
	s.AllowResize = false;
	s.ShowMaximizeButton = false;
	s.ShowFooter = false;
	s.ShowOnPageLoad = true;
	s.SetContent(() =>
	{
		using (Html.BeginForm("EditMailNotification", "Misc", FormMethod.Post, new { id = "mailNotificationEditForm" }))
		{
			ViewContext.Writer.Write("<div class='editFormWrapper'>");

			ViewContext.Writer.Write("<input type=\"hidden\" value=\"" + Model.Id + "\" id=\"Id\" name=\"Id\" />");
			ViewContext.Writer.Write("<input type=\"hidden\" value=\"" + Model.CronExpression + "\" id=\"CronExpression\" name=\"CronExpression\" />");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.NotificationPluginSystemName, "Benachrichtigungs-Plugin:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.NotificationPluginSystemName).ToHtmlString());
					Html.DevExpress().ComboBoxFor(m => m.NotificationPluginSystemName, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
						t.Properties.ValueField = "SystemName";
						t.Properties.ValueType = typeof(string);
						t.Properties.TextField = "Name";
						t.Properties.ClientSideEvents.SelectedIndexChanged = "function (s, e) { onNotificationPluginSelectedIndexChanged(); }";
					}).BindList(ViewData["AllNotificationPlugins"]).Bind(Model.NotificationPluginSystemName).Render();
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
				{
					if (Model == null || (Model != null && Model.NotificationPlugin == null))
						ViewContext.Writer.Write("<div id=\"notificationPluginDescription\" class=\"notificationDescription\"></div>");
					else
						ViewContext.Writer.Write(
							"<div id=\"notificationPluginDescription\" class=\"notificationDescription\">" + Model.NotificationPlugin.Description + "</div>");
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.NotificationJobSystemName, "Benachrichtigungs-Job:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.NotificationJobSystemName).ToHtmlString());
					ViewContext.Writer.Write(Html.Partial("~/Views/Misc/_MailNotificationPluginJobsPartial.cshtml", Model).ToHtmlString());
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
				{
					if (Model == null || (Model != null && Model.NotificationPlugin == null))
						ViewContext.Writer.Write("<div id=\"notificationJobDescription\" class=\"notificationDescription\"></div>");
					else
					{
						var notificationJob = Model.NotificationPlugin.AvailableNotificationJobs
							.FirstOrDefault(j => j.SystemName == Model.NotificationJobSystemName);

						if (notificationJob != null)
							ViewContext.Writer.Write(
								"<div id=\"notificationJobDescription\" class=\"notificationDescription\">" + notificationJob.Description + "</div>");
					}
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 65%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.UserValues, "Benutzer:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.UserValues).ToHtmlString());
					Html.DevExpress().DropDownEdit(t =>
					{
						t.Name = "devDropDownListUserValues";
						t.Width = new Unit(100, UnitType.Percentage);
						t.Text = Model.UserDescription;

						t.SetDropDownWindowTemplateContent(l =>
						{
							Html.DevExpress().ListBox(lb =>
							{
								lb.Name = "UserValues";
								lb.Width = new Unit(100, UnitType.Percentage);
								lb.Height = new Unit(250, UnitType.Pixel);
								lb.Properties.TextField = "Description";
								lb.Properties.ValueField = "Id";
								lb.Properties.ValueType = typeof(int);
								lb.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
								lb.ControlStyle.Border.BorderStyle = BorderStyle.None;
								lb.PreRender = (sender, e) =>
								{
									var listBox = sender as MVCxListBox;

									foreach (ListEditItem listItem in listBox.Items)
									{
										if (Model.UserValues == null || !Model.UserValues.Any(m => m == (int)listItem.Value)) continue;

										listItem.Selected = true;
									}
								};
								lb.Properties.ClientSideEvents.SelectedIndexChanged = "function (s, e) { onListBoxSelectionChanged(s, e); }";
							}).BindList(ViewData["AllUsersWithRole"]).Render();

							t.Properties.ClientSideEvents.TextChanged = "function (s, e) { synchronizeListBoxValues(s, e); }";
							t.Properties.ClientSideEvents.DropDown = "function (s, e) { synchronizeListBoxValues(s, e); }";
						});
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.CronExpression, "Interval:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.CronExpression).ToHtmlString());
					//ViewContext.Writer.Write("<div id=\"cronExpressionEditor\"></div>");
					//ViewContext.Writer.Write("<div id=\"cronExpressionDisplay\"></div>");
					ViewContext.Writer.Write(Html.Partial("~/Views/Misc/_MailNotificationCronPartial.cshtml").ToHtmlString());
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("</div>");

			Html.RenderPartial(
				"~/Views/Shared/_PopupButtonPanel.cshtml",
				new GreenTree.Nachtragsmanagement.Web.Models.Global.PopupModel
				{
					PopupName = "devPopupControlEditMailNotification",
					AcceptFunction = "function (s, e) { saveMailNotification(); }"
				}
			);
		}
	});
	s.Styles.Content.Paddings.Padding = new Unit(0);
	s.Styles.ModalBackground.Opacity = 0;
}).GetHtml()

</div>