@using GreenTree.Nachtragsmanagement.Core.Domain.User;
@using GreenTree.Nachtragsmanagement.Web.Extensions
@using GreenTree.Nachtragsmanagement.Web.Framework.Extension.DevExpress;

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

<div class="roleEditContainer">
	<script>
		var textSeparator = ", ";
		var checkedNodesText = "";
		var checkedNodesCounter = 0;

		function saveRole() {
			var form = $("#roleEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditRole", "Admin")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".roleEditContainer").remove();
							if (response == "success") {
								devGridViewRole.PerformCallback();
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function synchronizeTreeViewValues(s, e) {
			var treeView = MVCxClientTreeView.Cast(s);
			var node = treeView.GetNodeByName(e.node.name);
			if (node.GetChecked()) {
				while (node) {
					node.SetChecked(true);
					if (node.parent) {
						node = treeView.GetNodeByName(node.parent.name);
					} else {
						node = null;
					}
				}
			}
			checkedNodesText = "";
			checkedNodesCounter = 0;

			$("#roleEditForm").children(".hiddenRoleVal").remove();
			getCheckedNodesText(treeView.GetRootNode());
			devDropDownListFunctionValues.SetText(checkedNodesText.substr(0, checkedNodesText.length - textSeparator.length));
		}

		function getCheckedNodesText(parent) {
			for (var i = 0; i < parent.GetNodeCount(); i++) {
				if (parent.GetNode(i).GetChecked()) {
					checkedNodesText = checkedNodesText + parent.GetNode(i).GetText() + textSeparator;
					$("#roleEditForm").append('<input class="hiddenRoleVal" type="hidden" name="FunctionValues[' + checkedNodesCounter + ']" value="' + parent.GetNode(i).name + '" />');
					checkedNodesCounter++;
				}
				if (parent.GetNode(i).GetNodeCount() != 0) {
					getCheckedNodesText(parent.GetNode(i));
				}
			}
		}
	</script>

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

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

	s.Modal = true;
	s.Width = new Unit(400, UnitType.Pixel);
	s.CloseAction = CloseAction.CloseButton;
	s.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
	s.PopupVerticalAlign = PopupVerticalAlign.TopSides;
	s.PopupVerticalOffset = 10;
	s.AllowDragging = false;
	s.AllowResize = false;
	s.ShowFooter = false;
	s.ShowOnPageLoad = true;
	s.SetContent(() =>
	{
		using (Html.BeginForm("EditRole", "Admin", FormMethod.Post, new { id = "roleEditForm" }))
		{
			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.FunctionValues, "Funktionen:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.FunctionValues).ToHtmlString());
			Html.DevExpress().DropDownEdit(t =>
			{
				t.Name = "devDropDownListFunctionValues";
				t.Width = new Unit(100, UnitType.Percentage);

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

				t.SetDropDownWindowTemplateContent(l =>
				{
					ViewContext.Writer.Write("<div style='width: auto; overflow: auto; max-height: 200px'>");
					Html.DevExpress().TreeView(tv =>
					{
						var allFunctions = ViewData["AllFunctions"] as IList<Function>;

						tv.Name = "devTreeViewFunctionValues";
						tv.AllowCheckNodes = true;

						tv.CreateGroupedFunctionList(allFunctions);

						foreach (var checkedFunction in Model.FunctionValues)
						{
							tv.Nodes.FindRecursive(n => n.Name == checkedFunction.ToString()).Checked = true;
						}

						tv.ClientSideEvents.CheckedChanged = "function (s, e) { synchronizeTreeViewValues(s, e); }";
						tv.ClientSideEvents.Init = "function (s, e) { getCheckedNodesText(s.GetRootNode()); }";
					}).Render();
					ViewContext.Writer.Write("</div>");
				});
			}).Render();

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

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Level, "Stufe:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Level).ToHtmlString());
			Html.DevExpress().SpinEditFor(m => m.Level, t =>
			{
				t.Width = new Unit(60, UnitType.Percentage);
				t.Properties.NumberType = SpinEditNumberType.Integer;
				t.Properties.MinValue = 0;
			}).Render();

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.SeeOnlyAssigned, "Kann nur zugewiesene Baustellen einsehen:"));
					ViewContext.Writer.Write("<div style=\"overflow: hidden\">");
					{
						ViewContext.Writer.Write("<div style=\"float: left\">");
						{
							Html.DevExpress().RadioButtonFor(m => m.SeeOnlyAssigned, t =>
							{
								t.Text = "Ja";
								t.GroupName = "seeOnlyAssigned";
							}).Render();
						}
						ViewContext.Writer.Write("</div>");

						ViewContext.Writer.Write("<div style=\"float: left; margin-left: 8px\">");
						{
							Html.DevExpress().RadioButton(t =>
							{
								t.Name = "seeOnlyAssignedFalse";
								t.Text = "Nein";
								t.GroupName = "seeOnlyAssigned";
								t.Checked = !Model.SeeOnlyAssigned;
							}).Render();
						}
						ViewContext.Writer.Write("</div>");
					}
					ViewContext.Writer.Write("</div>");
				}
				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 = "devPopupControlEditRole",
					AcceptFunction = "function (s, e) { saveRole(); }"
				}
			);
		}
	});
	s.Styles.Content.Paddings.Padding = new Unit(0);
	s.Styles.ModalBackground.Opacity = 0;
}).GetHtml()
</div>