@using GreenTree.Nachtragsmanagement.Web.Extensions

@model GreenTree.Nachtragsmanagement.Web.Models.Admin.User.UserDataModel

<div class="userEditContainer">
	<script>
		var textSeparator = ", ";

		function saveUser() {
			var form = $("#userEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditUser", "Admin")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".userEditContainer").remove();
							if (response == "success") {
								devGridViewUser.PerformCallback();
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function onListBoxSelectionChanged(s, e) {
			if (e.index == 0)
				e.isSelected ? s.SelectAll() : s.UnselectAll();
			updateSelectAllItemState();
			updateText();
		}
		function updateSelectAllItemState() {
			isAllSelected() ? RoleValues.SelectIndices([0]) : RoleValues.UnselectIndices([0]);
		}
		function isAllSelected() {
			for (var i = 1; i < RoleValues.GetItemCount(); i++)
				if (!RoleValues.GetItem(i).selected)
					return false;
			return true;
		}
		function updateText() {
			var selectedItems = RoleValues.GetSelectedItems();
			devDropDownListRoleValues.SetText(getSelectedItemsText(selectedItems));
		}
		function synchronizeListBoxValues(s, e) {
			RoleValues.UnselectAll();
			var texts = s.GetText().split(textSeparator);
			var values = getValuesByTexts(texts);
			RoleValues.SelectValues(values);
			updateSelectAllItemState();
			updateText();
		}
		function getSelectedItemsText(items) {
			var texts = [];
			for (var i = 0; i < items.length; i++)
				if (items[i].index != 0)
					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 = RoleValues.FindItemByText(texts[i]);
				if (item != null)
					actualValues.push(item.value);
			}
			return actualValues;
		}
	</script>

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

	if (Model.Id == -1)
		s.HeaderText = "Neuen Benutzer erstellen";
	else
		s.HeaderText = "\"" + Model.Lastname + ", " + Model.Forename + "\" bearbeiten";

	s.Modal = true;
	s.Width = new Unit(400, UnitType.Pixel);
	s.CloseAction = CloseAction.CloseButton;
	s.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
	s.PopupVerticalAlign = PopupVerticalAlign.WindowCenter;
	s.AllowDragging = false;
	s.AllowResize = false;
	s.ShowFooter = false;
	s.ShowOnPageLoad = true;
	s.SetContent(() =>
	{
		using (Html.BeginForm("EditUser", "Admin", FormMethod.Post, new { id = "userEditForm" }))
		{
			ViewContext.Writer.Write("<div class='editFormWrapper'>");

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

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.CustomNumber, "Personalnummer:"));
			Html.DevExpress().TextBoxFor(m => m.CustomNumber, t =>
			{
				t.Width = new Unit(60, UnitType.Percentage);
			}).Render();

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Forename, "Vorname:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Forename).ToHtmlString());
					Html.DevExpress().TextBoxFor(m => m.Forename, t =>
					{
						t.Width = new Unit(95, UnitType.Percentage);
					}).Render();
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Lastname, "Nachname:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Lastname).ToHtmlString());
					Html.DevExpress().TextBoxFor(m => m.Lastname, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
					}).Render();
				ViewContext.Writer.Write("</div>");
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.MailAddress, "E-Mail:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.MailAddress).ToHtmlString());
			Html.DevExpress().TextBoxFor(m => m.MailAddress, t =>
			{
				t.Width = new Unit(100, UnitType.Percentage);
			}).Render();

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Password, "Passwort:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Password).ToHtmlString());
			Html.DevExpress().TextBoxFor(m => m.Password, t =>
			{
				t.Width = new Unit(60, UnitType.Percentage);
				t.Properties.Password = true;
			}).Render();

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.RoleValues, "Rollen:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.RoleValues).ToHtmlString());
			Html.DevExpress().DropDownEdit(t =>
			{
				t.Name = "devDropDownListRoleValues";
				t.Width = new Unit(100, UnitType.Percentage);

				if (Model.RoleDescriptions != null && Model.RoleDescriptions.Any())
					t.Text = String.Join(", ", Model.RoleDescriptions);

				t.SetDropDownWindowTemplateContent(l =>
				{
					Html.DevExpress().ListBox(lb =>
					{
						lb.Name = "RoleValues";
						lb.Width = new Unit(100, UnitType.Percentage);
						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.RoleValues == null || !Model.RoleValues.Any(m => m == (int)listItem.Value)) continue;

								listItem.Selected = true;
							}

							listBox.Items.Insert(0, new ListEditItem("(Alle auswählen)", -1));
						};
						lb.Properties.ClientSideEvents.SelectedIndexChanged = "function (s, e) { onListBoxSelectionChanged(s, e); }";
					}).BindList(ViewData["AllRoles"]).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>");

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