<#@ template language="C#" HostSpecific="True" #>
<#@ output extension=".cshtml" #>
<#@ include file="..\..\ViewHead.include.t4" #>
@using C1.Web.Mvc.Grid
@addTagHelper "*, C1.Web.Mvc"
@model IEnumerable<<#= ViewDataTypeName #>>
<#
if(Options["AllowFiltering"] && Options["Filter"]["ColumnFilterTypes"].Length>0)
{
#>@{

    var filterTypes = new Dictionary<string, FilterType>() {
<#
	foreach (var columnFilterType in Options["Filter"]["ColumnFilterTypes"])
	{
#>
        {"<#= columnFilterType["Key"] #>", <#= columnFilterType["Value"] #> }, 
<#
	}
#>
    };
}
<# } #>
<#@ include file=".\ClientEvent.include.t4" #>

<c1-flex-grid<#
	PushIndentAndCount("c1-flex-grid"); // indent for attributes of c1-flex-grid tag
	ResetLineLength();

	// Id
	if (!string.IsNullOrEmpty(Options["Id"]))
	{
		WriteAttribute("id", Options["Id"]);
	}

	// AutoGenerateColumns
	if (!Options["AutoGenerateColumns"])
	{
		WriteAttribute("auto-generate-columns", "false");
	}

	// AllowAddNew
	if (Options["AllowAddNew"])
	{
		WriteAttribute("allow-add-new", "true");
	}

	// AllowDelete
	if (Options["AllowDelete"])
	{
		WriteAttribute("allow-delete", "true");
	}

	// AllowEdit
	if (!Options["AllowEdit"])
	{
		WriteAttribute("is-read-only", "true");
	}

	// ShowGroups
	if (!Options["ShowGroups"])
	{
		WriteAttribute("show-groups", "false");
	}

	// GroupHeaderFormat
	if (!string.IsNullOrEmpty(Options["GroupHeaderFormat"]))
	{
		WriteAttribute("group-header-format", Options["GroupHeaderFormat"]);
	}

	// AllowSorting
	if (!Options["AllowSorting"])
	{
		WriteAttribute("allow-sorting", "false");
	}

	// ShowSort
	if (!Options["ShowSort"])
	{
		WriteAttribute("show-sort", "false");
	}

	// SortRowIndex
	if (Options["SortRowIndex"]!=null)
	{
		WriteAttribute("sort-row-index", Options["SortRowIndex"]);
	}

	// FrozenColumns
	if (Options["FrozenColumns"]!=0)
	{
		WriteAttribute("frozen-columns", Options["FrozenColumns"]);
	}

	// FrozenRows
	if (Options["FrozenRows"]!=0)
	{
		WriteAttribute("frozen-rows", Options["FrozenRows"]);
	}

	// ScrollPosition
	if (Options["ScrollPosition"]["X"]!=0 && Options["ScrollPosition"]["Y"]!=0)
	{
		WriteAttribute("scroll-position", string.Format("new C1.Web.Mvc.Point({0}, {1})",
			Options["ScrollPosition"]["X"], Options["ScrollPosition"]["Y"]));
	}

	// CssClass
	if (!string.IsNullOrEmpty(Options["CssClass"]))
	{
		WriteAttribute("class", Options["CssClass"]);
	}

	// Width
	if (!string.IsNullOrEmpty(Options["OutputWidth"]))
	{
		WriteAttribute("width", Options["OutputWidth"]);
	}

	// Height
	if (!string.IsNullOrEmpty(Options["OutputHeight"]))
	{
		WriteAttribute("height", Options["OutputHeight"]);
	}

	// SelectionMode
	if (Options["SelectionMode"]!="SelectionMode.CellRange")
	{
		WriteAttribute("selection-mode", Options["SelectionMode"]);
	}

	// ChildItemsPath
	if (!string.IsNullOrEmpty(Options["ChildItemsPath"]))
	{
		WriteAttribute("child-items-path", Options["ChildItemsPath"]);
	}

	// TreeIndent
	if (Options["TreeIndent"]!=14)
	{
		WriteAttribute("tree-indent", Options["TreeIndent"]);
	}

	// AllowDragging
	if (Options["AllowDragging"] != "AllowDragging.Columns")
	{
		WriteAttribute("allow-dragging", Options["AllowDragging"]);
	}

	// AllowMerging
	if (Options["AllowMerging"] != "AllowMerging.None")
	{
		WriteAttribute("allow-merging", Options["AllowMerging"]);
	}

	// AllowResizing
	if (Options["AllowResizing"] != "AllowResizing.Columns")
	{
		WriteAttribute("allow-resizing", Options["AllowResizing"]);
	}

	// AutoSizeMode
	if (Options["AutoSizeMode"] != "AutoSizeMode.Both")
	{
		WriteAttribute("auto-size-mode", Options["AutoSizeMode"]);
	}

	// HeadersVisibility
	if (Options["HeadersVisibility"] != "HeadersVisibility.All")
	{
		WriteAttribute("headers-visibility", Options["HeadersVisibility"]);
	}

	// AutoClipboard
	if (!Options["AutoClipboard"])
	{
		WriteAttribute("auto-clipboard", "false");
	}

	// DeferResizing
	if (Options["DeferResizing"])
	{
		WriteAttribute("defer-resizing", "true");
	}

	// ClientEvents
	foreach (var clientEvent in Options["ClientEvents"])
	{
		if (clientEvent["Handled"])
		{
			var eventName = clientEvent["Name"].Replace("OnClient","");
			var eventTagName = GetTagHelperName(eventName);
			eventName = eventName.Substring(0, 1).ToLower() + eventName.Substring(1);
			WriteAttribute(eventTagName, eventName);
		}
	}

	PopIndentAndCount(); //remove indent for attributes of c1-flex-grid tag

	#>><#

	WriteLine("");
	PushIndentAndCount(DEFAULT_INDENT); //indent for all child tags of grid.

	//c1-items-source tag
	#><c1-items-source<#

	PushIndentAndCount("c1-items-source"); //indent for attributes of c1-items-source
	ResetLineLength();
	if (!string.IsNullOrEmpty(Options["ReadActionUrl"]))
	{
		WriteAttribute("read-action-url", String.Format("@(Url.Action(\"{0}\"))", Options["ReadActionUrl"]));
	}
	else
	{
		WriteAttribute("source-collection", "Model");
	}

	// Create
	if (!string.IsNullOrEmpty(Options["CreateActionUrl"]) && Options["AllowAddNew"] && !Options["BatchEdit"])
	{
		WriteAttribute("create-action-url", String.Format("@(Url.Action(\"{0}\"))", Options["CreateActionUrl"]));
	}

	// Update
	if (!string.IsNullOrEmpty(Options["UpdateActionUrl"]) && Options["AllowEdit"] && !Options["BatchEdit"])
	{
		WriteAttribute("update-action-url", String.Format("@(Url.Action(\"{0}\"))", Options["UpdateActionUrl"]));
	}

	// Delete
	if (!string.IsNullOrEmpty(Options["DeleteActionUrl"]) && Options["AllowDelete"] && !Options["BatchEdit"])
	{
		WriteAttribute("delete-action-url", String.Format("@(Url.Action(\"{0}\"))", Options["DeleteActionUrl"]));
	}

	// BatchEdit
	if (!string.IsNullOrEmpty(Options["BatchEditActionUrl"]) && Options["BatchEdit"])
	{
		WriteAttribute("batch-edit-action-url", String.Format("@(Url.Action(\"{0}\"))", Options["BatchEditActionUrl"]));
	}

	// DisableServerRead
	if (Options["DisableServerRead"])
	{
		WriteAttribute("disable-server-read", "true");
	}

	// InitialItemsCount
	if (Options["InitialItemsCount"]!=null)
	{
		WriteAttribute("initial-items-count", Options["InitialItemsCount"]);
	}

	// PageIndex
	if (Options["AllowPaging"] && Options["PageIndex"]>0)
	{
		WriteAttribute("page-index", Options["PageIndex"]);
	}

	// PageSize
	if (Options["AllowPaging"] && Options["PageSize"]>0)
	{
		WriteAttribute("page-size", Options["PageSize"]);
	}

	// Group
	var groupString="";
	foreach (var group in Options["GroupDescriptions"])
	{
		if (group["Enabled"])
		{
			groupString += group["PropertyName"] + ",";
		}
	}

	if (!string.IsNullOrEmpty(groupString))
	{
		groupString = groupString.TrimEnd(',');
		WriteAttribute("group-by", groupString);
	}
		
	// Sort
	var sortString="";
	foreach (var sort in Options["SortDescriptions"])
	{
		if (sort["Enabled"])
		{
			sortString += sort["Property"];
			sortString += sort["Ascending"]? "" : " DESC";
			sortString += ",";
		}
	}
	if (!string.IsNullOrEmpty(sortString))
	{
		sortString = sortString.TrimEnd(',');
		WriteAttribute("order-by", sortString);
	}

	PopIndentAndCount(); //remove indent for attributes of c1-items-source tag.
	#>></c1-items-source><#
	// Columns
	var columns = Options["Columns"];
	if(!Options["AutoGenerateColumns"] && columns.Length>0)
	{
		foreach (var column in columns)
		{
			WriteLine("");

			#><c1-flex-grid-column<#

			PushIndentAndCount("c1-items-source"); //indent fro attributes of c1-flex-grid-column.
			ResetLineLength();

			// AllowDragging
			if(!column["AllowDragging"])
			{
				WriteAttribute("allow-dragging", "false");
			}
			
			// AllowMerging
			if(column["AllowMerging"])
			{
				WriteAttribute("allow-merging", "true");
			}

			// AllowResizing
			if(!column["AllowResizing"])
			{
				WriteAttribute("allow-resizing", "false");
			}

			// CssClass
			if(!string.IsNullOrEmpty(column["CssClass"]))
			{
				WriteAttribute("class", column["CssClass"]);
			}

			// IsContentHtml
			if(column["IsContentHtml"])
			{
				WriteAttribute("is-content-html", "true");
			}

			// IsReadOnly
			if(column["IsReadOnly"])
			{
				WriteAttribute("is-read-only", "true");
			}

			// IsSelected
			if(column["IsSelected"])
			{
				WriteAttribute("is-selected", "true");
			}

			// Visible
			if(!column["Visible"])
			{
				WriteAttribute("is-visible", "false");
			}

			// WordWrap
			if(column["WordWrap"])
			{
				WriteAttribute("word-wrap", "true");
			}

			// Aggregate
			if(column["Aggregate"]!="Aggregate.None")
			{
				WriteAttribute("aggregate", column["Aggregate"]);
			}

			// Align
			if(!string.IsNullOrEmpty(column["Align"]))
			{
				WriteAttribute("align", column["Align"]);
			}

			// AllowSorting
			if(!column["AllowSorting"])
			{
				WriteAttribute("allow-sorting", "false");
			}

			// Binding
			if(!string.IsNullOrEmpty(column["Binding"]))
			{
				WriteAttribute("binding", column["Binding"]);
			}

			// DataType
			if(!string.IsNullOrEmpty(column["DataType"]))
			{
				WriteAttribute("c1-data-type", column["DataType"]);
			}

			// Format
			if(!string.IsNullOrEmpty(column["Format"]))
			{
				WriteAttribute("format", column["Format"]);
			}

			// Header
			if(!string.IsNullOrEmpty(column["Header"]))
			{
				WriteAttribute("header", column["Header"]);
			}

			// Mask
			if(!string.IsNullOrEmpty(column["Mask"]))
			{
				WriteAttribute("mask", column["Mask"]);
			}

			// MaxWidth
			if(column["MaxWidth"]!=null)
			{
				WriteAttribute("max-width", column["MaxWidth"]);
			}

			// MinWidth
			if(column["MinWidth"]!=null)
			{
				WriteAttribute("min-width", column["MinWidth"]);
			}

			// Name
			if(!string.IsNullOrEmpty(column["Name"]))
			{
				WriteAttribute("name", column["Name"]);
			}

			// Width
			if(!string.IsNullOrEmpty(column["Width"]))
			{
				WriteAttribute("width", column["Width"]);
			}

			// SortMemberPath
			if(!string.IsNullOrEmpty(column["SortMemberPath"]))
			{
				WriteAttribute("sort-member-path", column["SortMemberPath"]);
			}
			#>><#

			PopIndentAndCount(); //remove indent of column attributes.

			// DataMap
			var dataMap = column["DataMap"];
			if(dataMap["IsValid"])
			{
				PushIndentAndCount(DEFAULT_INDENT); //indent for child tags of column
				WriteLine("");

			#><c1-data-map<#

				PushIndentAndCount("c1-data-map"); //indent for attributes of c1-data-map
				ResetLineLength();
				WriteAttribute("display-member-path", dataMap["DisplayMemberPath"]);
				WriteAttribute("selected-value-path", dataMap["SelectedValuePath"]);
				#>><#
				PopIndentAndCount(); //remove indent for attributes of c1-data-map
				PushIndentAndCount(DEFAULT_INDENT); //indent for child tags of datamap
				WriteLine("");

				//ItemsSource
				#><c1-items-source<#
				PushIndentAndCount("c1-items-source"); //indent for attributes of c1-items-source
				ResetLineLength();
				if(dataMap["UseRemoteBinding"])
				{
					WriteAttribute("read-action-url", String.Format("@(Url.Action(\"{0}\"))", dataMap["ReadActionUrl"]));
				}
				else
				{
					WriteAttribute("source-collection", string.Format("(IEnumerable<{0}>)ViewBag.{1}", 
						dataMap["Source"]["TypeName"], dataMap["ViewBagName"]));
				}
				PopIndentAndCount(); //remove indent for attributes of c1-items-source
				#>></c1-items-source><# 
				PopIndentAndCount(); //remove indent for child tags of datamap
				WriteLine("");
				#></c1-data-map><#
				PopIndentAndCount(); //remove indent for child tags of column
				WriteLine("");
			}
			#></c1-flex-grid-column><#
		}
	}

	// Filter
	if(Options["AllowFiltering"])
	{
		var filter = Options["Filter"];
		WriteLine("");
		#><c1-flex-grid-filter<#
		PushIndentAndCount("c1-flex-grid-filter"); //indent for attributes of c1-flex-grid-filter
		ResetLineLength();

		WriteAttribute("default-filter-type", filter["DefaultFilterType"]);

		if(!filter["ShowFilterIcons"])
		{
			WriteAttribute("show-filter-icons", "false");
		}

		if(!filter["ShowSortButtons"])
		{
			WriteAttribute("show-sort-buttons", "false");
		}
		PopIndentAndCount();
		#>><#
		if(filter["ColumnFilterTypes"].Length > 0)
		{
			PushIndentAndCount(DEFAULT_INDENT);
			foreach (var columnFilterType in filter["ColumnFilterTypes"])
			{
				WriteLine("");
		#><c1-flex-grid-column-filter<#
				PushIndentAndCount("c1-flex-grid-column-filter"); //indent for attributes of c1-flex-grid-column-filter
				ResetLineLength();
				WriteAttribute("column", columnFilterType["Key"]);
				WriteAttribute("filter-type", columnFilterType["Value"]);
				PopIndentAndCount();
		#>></c1-flex-grid-column-filter><#
			}
			PopIndentAndCount();
			WriteLine("");
		}
		#></c1-flex-grid-filter><#
	}

	// GroupPanelSettings
	if(Options["ShowGroupPanel"])
	{
		var groupPanel = Options["GroupPanelSettings"];
		WriteLine("");
		#><c1-flex-grid-group-panel<#
		PushIndentAndCount("c1-flex-grid-group-panel"); //indent for attributes of c1-flex-grid-group-panel
		ResetLineLength();
		if(groupPanel["MaxGroups"]!=6)
		{
			WriteAttribute("max-groups", groupPanel["MaxGroups"]);
		}

		if(!string.IsNullOrEmpty(groupPanel["Selector"]))
		{
			WriteAttribute("selector", groupPanel["Selector"]);
		}

		if(!string.IsNullOrEmpty(groupPanel["Placeholder"]))
		{
			WriteAttribute("placeholder", groupPanel["Placeholder"]);
		}

		if(!groupPanel["HideGroupedColumns"])
		{
			WriteAttribute("hide-grouped-columns", "false");
		}

		PopIndentAndCount(); //remove indent for attributes of c1-flex-grid-group-panel
		#>></c1-flex-grid-group-panel><#
	}

	PopIndentAndCount();
	WriteLine("");
	#></c1-flex-grid>
<#
	if(Options["AllowPaging"] && !string.IsNullOrEmpty(Options["Id"]))
	{
		#><c1-pager owner="<#= Options["Id"] #>"></c1-pager>
<#
	}
 #>

<#+

const string DEFAULT_INDENT = "    ";
const int MAX_LINE_LENGTH = 120;
int indentLength = 0;
int lineLength = 0; //default line-length

//Get the indent for attributes of current tag.
static string GetIndent(string tagName)
{
	string content = "<" + tagName + " ";
	string indent = "";
	for(var i=0; i<content.Length; i++){
		indent += " ";
	}
	return indent;
}

static string GetTagHelperName(string name)
{
    return string.Join("", name.Select((c, index) =>
    {
        if (c >= 'A' && c <= 'Z' && index > 0)
        {
            return "-" + c.ToString().ToLower();
        }
        else
        {
            return c.ToString().ToLower();
        }
    }));
}

private void PushIndentAndCount(string indent)
{
	if(indent != DEFAULT_INDENT)
	{
		indent = GetIndent(indent);
	}
	indentLength += indent.Length;
	PushIndent(indent);
}

private string PopIndentAndCount()
{
	string indent = PopIndent();
	indentLength -= indent.Length;
	return indent;
}

private void WriteAttribute(string attrName,object attrValue){
	string content = attrName + "=\"" + attrValue.ToString() + "\"";
	FormatLine(content);
	Write(content);
}

private void ResetLineLength()
{
	lineLength = indentLength;
}

private void FormatLine(int colsCount)
{
	if(lineLength + colsCount > MAX_LINE_LENGTH)
	{
		lineLength = colsCount + indentLength;
		WriteLine("");
	}
	else
	{
		lineLength += colsCount + 1; //the seprate space takes 1 length
		Write(" ");
	}
}

private void FormatLine(string content)
{
	FormatLine(content.Length);
}

#>