@inherits Dynamicweb.Rendering.RazorTemplateBase<Dynamicweb.Rendering.RazorTemplateModel<Dynamicweb.Rendering.Template>>

@functions {
	private string GetFontStack()
	{
		return "font-family:initial,Arial,Helvetica Neue,Helvetica,sans-serif;";
	}

	private string GetTableReset()
	{
		return "border:0;margin:0;outline:0;padding:0;";
	}

	private Dynamicweb.Frontend.ColorViewModel GetMutedColor(string hex, int percent, double threshold = 0.5)
	{
		/// <summary>
		/// Return a color in either lighter or darker contrast based on the original color luminance.
		/// </summary>
		/// <param name="percent">The percent (1-100) to darken or light the color with - higher percentage will give higher contrast</param>
		/// <param name="threshold">The luminance threshold (0-1). Default is 0.5. 0 is black, 1 is white. Luminance threshold is used to decide wether the returned contrast color should be darker or lighter than the base color</param>
		/// <returns>A new color viewmodel with the contrasted color in either darker or lighter luminance compared to base color</returns>
		/// 
		if (threshold > 1)
			threshold = 1;
		if (threshold < 0)
			threshold = 0;

		var color = Dynamicweb.Imaging.Colors.Color.FromHex(hex);
		var luminance = (0.2126 * color.BaseColor.R) + (0.7152 * color.BaseColor.G) + (0.0722 * color.BaseColor.B);
		/// == luminance = 0 is black, luminance = 1 is white == //
		luminance = color.Brightness / 255;
		return luminance < threshold ? new Dynamicweb.Frontend.ColorViewModel() { Hex = color.Lighten(percent).ToHex() } : new Dynamicweb.Frontend.ColorViewModel() { Hex = color.Darken(percent).ToHex() };
	}
	
	private static double GetImageHeight(string imageRatio, double imageWidth)
	{
		string[] ratioValues = imageRatio.Split('-');
		double ratio = ratioValues.Length == 2 ? Dynamicweb.Core.Converter.ToDouble(ratioValues[1]) / Dynamicweb.Core.Converter.ToDouble(ratioValues[0]) : 1;
		return imageWidth * ratio;
	}
}

@{
	var page = Dynamicweb.Content.Services.Pages.GetPage(Pageview.ID);
	var item = Pageview.CurrentParagraph.Item;
	var settings = Dynamicweb.Frontend.ContentViewModelFactory.CreatePageInfoViewModel(page?.Parent).Item;
	var block = Pageview.CurrentParagraph.Item;

	bool hideProductNumber = Dynamicweb.Core.Converter.ToBoolean(item["HideProductNumber"].ToString());

	int cellSpacing = 8;
	string align = block["Align"].ToString();
	var layoutColumns = Dynamicweb.Core.Converter.ToInt32(block["Layout"].ToString());

	IList<LoopItem> products = GetLoop("Products");
}

@if (products.Any())
{
	@:<tr style="@GetTableReset()">

	int index = 1;
	int totalProducts = products.Count();
	foreach (var product in products)
	{
		string variantId = product.GetString("Ecom:Product.VariantID");
		string defaultVariantId = product.GetString("Ecom:Product.DefaultVariantComboID");

		string variantIdForLink = !string.IsNullOrEmpty(variantId) ? $"&VariantID={variantId}" : string.Empty;
		variantIdForLink = string.IsNullOrEmpty(variantIdForLink) && !string.IsNullOrEmpty(defaultVariantId) ? $"&VariantID={defaultVariantId}" : variantIdForLink;

		string link = "Default.aspx?ID=" + GetPageIdByNavigationTag("Shop");
		link += $"&GroupID={product.GetString("Ecom:Product.PrimaryGroupID")}";
		link += $"&ProductID={product.GetString("Ecom:Product.ID")}";
		link += variantIdForLink;
		link = Dynamicweb.Frontend.SearchEngineFriendlyURLs.GetFriendlyUrl(link);

		string imagePath = product.GetString("Ecom:Product.PrimaryImage");

		<td valign="top" style="@GetTableReset()">
			<table style="border-collapse:collapse;table-layout:fixed;@GetTableReset()" cellpadding="0" cellspacing="0" width="100%" role="presentation">
				<tbody>
					<tr style="@GetTableReset()">
						<td style="@GetTableReset()">
							<div align="center" style="font-size:2px;">
								<a style="text-decoration:none;@GetTableReset()" href="@link" target="_blank">
									@if (!string.IsNullOrEmpty(imagePath))
									{
										imagePath = Dynamicweb.Context.Current.Server.UrlEncode(imagePath);

										int columnWidth = 640;
										int columnCount = Dynamicweb.Core.Converter.ToInt32(Pageview.CurrentParagraph.Item["Layout"] != null ? Pageview.CurrentParagraph.Item["Layout"].ToString() : "2");
										int padding = Dynamicweb.Core.Converter.ToInt32(Pageview.CurrentParagraph.Item["Padding"] != null ? Pageview.CurrentParagraph.Item["Padding"].ToString() : "0");
										padding = (padding * 2) + (8 * (columnCount - 1));

										var imageWidth = (columnWidth - padding) / columnCount;
										string image = $"/Admin/Public/GetImage.ashx?width={imageWidth}";

										string crop = "7";

										var ratio = Pageview.CurrentParagraph.Item["ImageAspectRatio"] != null ? Pageview.CurrentParagraph.Item["ImageAspectRatio"].ToString() : "4-3";
										if (ratio != "original")
										{
											if (!string.IsNullOrEmpty(ratio))
											{
												image += $"&height={GetImageHeight(ratio, imageWidth)}";
												image += $"&fillcanvas=true";
											}
										}

										image += $"&crop={crop}&image={imagePath}&format=webp";

										string alt = product.GetString("Ecom:Product.Name");

										<img src="@image" align="center" style="display:block;border-collapse:separate;border-spacing:0;border:0;margin:0;outline:0;padding:0;height:auto;width:100%;max-width:@(imageWidth)px;" alt="@alt" width="@(imageWidth)">
									}
								</a>
							</div>

							<table style="border-collapse:collapse;table-layout:fixed;@GetTableReset()" cellpadding="0" cellspacing="0" width="100%" role="presentation">
								<tbody>
									<tr style="@GetTableReset()">
										<td style="@GetTableReset()padding-top:8px;text-align:@align;line-height:18px;font-size:13px;text-decoration:none;">
											<a style="text-decoration:none;@GetTableReset()" href="@link" target="_blank">
												@product.GetString("Ecom:Product.Name")
											</a>
										</td>
									</tr>

									@if (!hideProductNumber)
									{
										<tr>
											<td style="@GetTableReset()padding-top:8px;line-height:18px;font-size:11px;">
												@product.GetString("Ecom:Product.Number")
											</td>
										</tr>
									}
									<tr><td height="24" style="padding-top:24px;"></td></tr>
								</tbody>
							</table>
						</td>
					</tr>
				</tbody>
			</table>
		</td>

		if (index % layoutColumns == 0 && !(index == totalProducts))
		{
			@:</tr>
			@:<tr style="@GetTableReset()">
				@:<td style="@GetTableReset()" colspan="100%" height="@(cellSpacing * 4)">&nbsp;</td>
			@:</tr>
			@:<tr style="@GetTableReset()">
		}
		else
		{
			if(!(index == totalProducts))
			{ 
				@:<td width="@(cellSpacing)" style="@GetTableReset()">&nbsp;</td>
			}
		}

		index++;
	}
	@:</tr>
}
