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

@{
	AddScript("/Files/Templates/Designs/Swift-v2/Assets/lib/swiffy-slider/dist/js/swiffy-slider.min.js");
	AddStylesheet("/Files/Templates/Designs/Swift-v2/Assets/lib/swiffy-slider/dist/css/swiffy-slider.min.css");
	
	ProductViewModel product = null;
	if (Dynamicweb.Context.Current.Items.Contains("ProductDetails"))
	{
		product = (ProductViewModel)Dynamicweb.Context.Current.Items["ProductDetails"];
	}

	string layout = Model.Item.GetRawValueString("Layout") == "slider" ? "ProductSliderComponent" : "ProductGridComponent";
	string lazyHeight = Model.Item.GetBoolean("SetMinHeightForLazyLoading") ? "min-height: 360px" : "";
	
	//Link generation
	string pageId = Model.Item.GetLink("ProductSliderServicePage") != null ? Model.Item.GetLink("ProductSliderServicePage").PageId.ToString() : "";
	string servicePageByNavigationTag = GetPageIdByNavigationTag("ProductSliderService") != 0 ? GetPageIdByNavigationTag("ProductSliderService").ToString() : "";
	pageId = pageId == "" ? servicePageByNavigationTag : pageId;

	string url = "/Default.aspx?ID=" + pageId;

	if (Pageview.IsVisualEditorMode)
	{
		url += "&VisualEdit=True";
	}

	url += $"&ProductListPartial={layout}"; //Use this to render either a slider or a grid

	//Source type
	string sourceType = Model.Item.GetRawValueString("RelationType", "trending");
	IList<string> relateFromProductIds = new List<string> { };
	IList<string> relateFromProductVariantIds = new List<string> { };
	IList<string> relateFromGroupIds = new List<string> { };
	bool hasVariants = false;
	ProductListViewModel relateToViewModel = Model.Item.GetValue<ProductListViewModel>("RelateTo");

	//--- PRODUCTS ---
	if (sourceType == "variants" || sourceType == "frequently" || sourceType == "selected")
	{
		if (relateToViewModel?.Products != null)
		{
			hasVariants = relateToViewModel.Products.Any(p => !string.IsNullOrEmpty(p.VariantId));
			foreach (var fromProduct in relateToViewModel.Products)
			{
				if (hasVariants)
				{
					if (!string.IsNullOrEmpty(fromProduct.VariantId))
					{
						relateFromProductVariantIds.Add($"{fromProduct.Id} {fromProduct.VariantId}");
					}
					else
					{
						relateFromProductVariantIds.Add($"{fromProduct.Id}");
					}
				}
				relateFromProductIds.Add($"{fromProduct.Id}");
			}
		}
	}

	//--- GROUPS ---
	if (sourceType == "most-sold" || sourceType == "trending" || sourceType == "latest" || sourceType == "custom")
	{
		var groupsToRelateTo = Model.Item.GetList("RelateTo")?.GetRawValue().OfType<string>().ToList();

		if (groupsToRelateTo != null) {
			foreach (var fromGroup in groupsToRelateTo)
			{
				var groupId = fromGroup.Length > 2 ? fromGroup.Remove(0, 2) : fromGroup;

				if (!fromGroup.Contains("p_"))
				{
					relateFromGroupIds.Add(groupId);
				}
			}
		}

		if (relateToViewModel?.Products != null)
		{
			foreach (var fromProduct in relateToViewModel.Products)
			{
				var groupId = fromProduct.PrimaryOrDefaultGroup.Id;
				relateFromGroupIds.Add(groupId);
			}
		}
	}

	string relationGroupId = Model.Item.GetRawValueString("RelationGroup", string.Empty);

	//--- RELATED GROUP ---
	if (sourceType == "related")
	{
		if (relateToViewModel?.Products != null)
		{
			product = relateToViewModel.Products.FirstOrDefault();
		}

		if (product?.RelatedGroups != null)
		{
			foreach (var relationGroup in product.RelatedGroups)
			{
				if (relationGroup.Id == relationGroupId) {
					hasVariants = relationGroup.Products.Any(p => !string.IsNullOrEmpty(p.VariantId));
					foreach (var fromProduct in relationGroup.Products)
					{
						if (hasVariants)
						{
							if (!string.IsNullOrEmpty(fromProduct.VariantId))
							{
								relateFromProductVariantIds.Add($"{fromProduct.ProductId} {fromProduct.VariantId}");
							}
							else
							{
								relateFromProductVariantIds.Add($"{fromProduct.ProductId}");
							}
						}
						relateFromProductIds.Add($"{fromProduct.ProductId}");
					}
				}
			}
		}
	}


	//Create group id collection and products id collection strings
	string productIds = relateFromProductIds.Count > 0 ? string.Join(",", relateFromProductIds) : "";
	string productVariantIds = relateFromProductVariantIds.Count > 0 ? string.Join(",", relateFromProductVariantIds) : "";
	string groupIds = relateFromGroupIds.Count > 0 ? string.Join(",", relateFromGroupIds) : "";

	if (product is object)
	{
		if (string.IsNullOrEmpty(productIds) && (sourceType == "variants" || sourceType == "frequently" || sourceType == "selected" || sourceType == "custom"))
		{
			productIds = product.Id;
		}

		if (string.IsNullOrEmpty(groupIds) && (sourceType == "most-sold" || sourceType == "trending" || sourceType == "latest"))
		{
			groupIds = product.PrimaryOrDefaultGroup.Id;
		}
	}
}

@*Container element for the request*@
@if (!string.IsNullOrEmpty(productIds) || !string.IsNullOrEmpty(groupIds) || (string.IsNullOrEmpty(productIds) && string.IsNullOrEmpty(groupIds) && sourceType != "related"))
{
	<form method="post" action="@url" id="ComponentSliderProductsForm_@Model.ID" data-response-target-element="ComponentSliderProducts_@Model.ID" data-preloader="inline" data-update-url="false" class="item_@Model.Item.SystemName.ToLower()">
		<input type="hidden" name="ParagraphId" value="@Model.ID" />
		<input type="hidden" name="SortOrder" value="DESC">
		<input type="hidden" name="SourceType" value="@sourceType">

		@if (!string.IsNullOrEmpty(groupIds))
		{
			<input type="hidden" name="GroupId" value="@groupIds">
		}
		@if (sourceType != "frequently" && sourceType != "variants" && !string.IsNullOrEmpty(productIds) && !hasVariants)
		{
			<input type="hidden" name="MainProductId" value="@productIds">
		}
		@if (sourceType != "frequently" && hasVariants)
		{
			<input type="hidden" name="ProductVariantId" value="@productVariantIds">
		}

		@if (Model.Item.GetInt32("ProductsCount") != 0)
		{
			<input type="hidden" name="PageSize" value="@Model.Item.GetInt32("ProductsCount")">
		}

		@if (sourceType == "variants")
		{
			<input type="hidden" name="MasterProductID" value="@productIds">
			<input type="hidden" name="isVariant" value="true">
		}
		@if (sourceType == "most-sold")
		{
			<input type="hidden" name="SortBy" value="OrderCount">
		}
		@if (sourceType == "trending")
		{
			<input type="hidden" name="SortBy" value="OrderCountGrowth">
		}
		@if (sourceType == "frequently" && !string.IsNullOrEmpty(productIds))
		{
			<input type="hidden" name="BoughtWithProductIds" value="[@productIds]">
		}
		@if (sourceType == "latest")
		{
			<input type="hidden" name="SortBy" value="Created">
		}
	</form>

	<div class="w-100 h-100" data-dw-colorscheme="@Model.ColorScheme?.Id">
		<div id="ComponentSliderProducts_@Model.ID" class="h-100" style="@lazyHeight"></div>
	</div>

	<script type="module">
		const productSliderContainer = document.querySelector("#ComponentSliderProducts_@Model.ID");
		const productSliderForm = document.querySelector("#ComponentSliderProductsForm_@Model.ID");

		swift.PageUpdater.Update(productSliderForm);
		productSliderForm.addEventListener("updated.swift.pageupdater", function(e){
			if (e.detail.html === "") {
				productSliderContainer.closest("[data-col-size]").classList.add("d-none");
			}
		});
	</script>
}
else if (Pageview.IsVisualEditorMode == true)
{
	<div class="alert alert-dark" role="alert">
		<span>@Translate("Product component slider: The slider will be rendered here, if there is anything to show")</span>
	</div>
}
