@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.ParagraphViewModel>
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Frontend

@{ 
	ProductViewModel product = new ProductViewModel();

	if (Dynamicweb.Context.Current.Items.Contains("ProductDetails"))
	{
		product = (ProductViewModel)Dynamicweb.Context.Current.Items["ProductDetails"];
	}

	string servicePageId = Model.Item.GetLink("ServicePage") != null ? Model.Item.GetLink("ServicePage").PageId.ToString() : "";
	servicePageId = servicePageId == "" && GetPageIdByNavigationTag("RelatedProductsListService") != 0 ? GetPageIdByNavigationTag("RelatedProductsListService").ToString() : servicePageId;
	string pageSize = Model.Item.GetInt32("PageSize") != 0 ? Model.Item.GetString("PageSize") : "10";

	IEnumerable<string> selectedDisplayGroups = Model.Item.GetList("Fields")?.GetRawValue().OfType<string>().ToList();
	string selectedDisplayGroupsString = selectedDisplayGroups.Count() > 0 ? (string.Join(",", selectedDisplayGroups.Select(x => x.ToString()).ToArray())) : "";

	string title = !string.IsNullOrEmpty(Model.Item.GetString("Title")) ? Model.Item.GetString("Title") : "";
	string hideTitle = Model.Item.GetBoolean("HideTitle").ToString();
	string hideImage = Model.Item.GetBoolean("HideImage").ToString();
	string hideProductNumber = Model.Item.GetBoolean("HideProductNumber").ToString();
	string hideProductName = Model.Item.GetBoolean("HideProductName").ToString();
	string hideStock = Model.Item.GetBoolean("HideStock").ToString();
	string quantitySelector = Model.Item.GetBoolean("QuantitySelector").ToString();
	string titleFontSize = Model.Item.GetRawValueString("TitleFontSize", "display-6");

	//Source type
	string sourceType = Model.Item.GetRawValueString("SourceType", "variants");
	IList<string> relateFromProductIds = new List<string>{};

	//--- RELATED PRODUCTS ---
	if (sourceType == "related-products" && product?.RelatedGroups != null) {
		foreach (var group in product.RelatedGroups)
		{
			foreach (var relatedProduct in group.Products)
			{
				if (string.IsNullOrEmpty(relatedProduct.VariantId))
				{
					relateFromProductIds.Add($"{relatedProduct.ProductId}");
				}
				else
				{
					relateFromProductIds.Add($"{relatedProduct.ProductId} {relatedProduct.VariantId}");
				}
			}
		}
	}

	//Create group id collection and products id collection strings
	string groupId = product?.PrimaryOrDefaultGroup?.Id ?? string.Empty;
	string productIds = sourceType == "related-products" ? string.Join(",", relateFromProductIds) : product?.Id;
}

@if (!Pageview.IsVisualEditorMode)
{
	<div id="RelatedProductsListContainer_@Pageview.CurrentParagraph.ID" class="item_@Model.Item.SystemName.ToLower()">
		@* Initial form for first load (We pass all the settings to the actual template) *@
		<form action="/Default.aspx?ID=@servicePageId" id="RelatedProductsListForm_@Pageview.CurrentParagraph.ID" data-response-target-element="RelatedProductsListContainer_@Pageview.CurrentParagraph.ID">
			<input type="hidden" name="SortOrder" value="DESC">
			<input type="hidden" name="ID" value="@servicePageId">
			<input type="hidden" name="SourceType" value="@sourceType">
			<input type="hidden" name="ParagraphID" value="@Pageview.CurrentParagraph.ID">
			<input type="hidden" name="PageSize" value="@pageSize" id="RelatedProductsListPageSize_@Pageview.CurrentParagraph.ID">
			<input type="hidden" name="PageSizeSetting" value="@pageSize">
			<input type="hidden" name="Title" value="@title">
			<input type="hidden" name="HideTitle" value="@hideTitle">
			<input type="hidden" name="SelectedDisplayGroups" value="@selectedDisplayGroupsString">
			<input type="hidden" name="HideImage" value="@hideImage">
			<input type="hidden" name="HideProductNumber" value="@hideProductNumber">
			<input type="hidden" name="HideProductName" value="@hideProductName">
			<input type="hidden" name="HideStock" value="@hideStock">
			<input type="hidden" name="QuantitySelector" value="@quantitySelector">
			<input type="hidden" name="TitleFontSize" value="@titleFontSize">

			@*--- VARIANTS ---*@
			@if (sourceType == "variants")
			{
				<input type="hidden" name="MasterProductID" value="@productIds">
				<input type="hidden" name="isVariant" value="true">
			}

			@*--- MOST SOLD ---*@
			@if (sourceType == "most-sold")
			{
				<input type="hidden" name="SortBy" value="OrderCount">
				<input type="hidden" name="GroupId" value="@groupId">
				<input type="hidden" name="isVariant" value="false">
			}

			@*--- TRENDING ---*@
			@if (sourceType == "trending")
			{
				<input type="hidden" name="SortBy" value="OrderCountGrowth">
				<input type="hidden" name="GroupId" value="@groupId">
				<input type="hidden" name="isVariant" value="false">
			}

			@*--- LATEST ---*@
			@if (sourceType == "latest")
			{
				<input type="hidden" name="SortBy" value="Created">
				<input type="hidden" name="GroupId" value="@groupId">
				<input type="hidden" name="isVariant" value="false">
			}

			@*--- FREQUENTLY BOUGHT ---*@
			@if (sourceType == "frequently")
			{
				<input type="hidden" name="BoughtWithProductIds" value="[@productIds]">
				<input type="hidden" name="isVariant" value="false">
			}

			@*--- RELATED PRODUCTS ---*@
			@if (sourceType == "related-products")
			{
				<input type="hidden" name="ProductvariantId" value="@productIds">
			}
		</form>
	</div>

	<script type="module">
		swift.PageUpdater.Update(document.querySelector("#RelatedProductsListForm_@Pageview.CurrentParagraph.ID"));
	</script>

	<script>
		 var UpdateRelatedProductsList = function(event, type, id) {
			var targetElement = "RelatedProductsListContainer_" + id;

			if (type == "UpdateFacets") {
				targetElement = "RelatedProductsListFacets_"  + id;
			}

			document.querySelector('#RelatedProductsListRequestType_' + id).value = type;
			document.querySelector('#RelatedProductsListForm_' + id).setAttribute("data-response-target-element", targetElement);

			swift.PageUpdater.Update(document.querySelector("#RelatedProductsListForm_" + id));
		};
	</script>
} else {
	<div class="alert alert-info" role="alert">
        <span>@Translate("Related products list")</span>
    </div>
}
