@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.ParagraphViewModel>
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Frontend
@using System.Text.RegularExpressions; 
@using System.IO

@functions {
	public ProductViewModel product { get; set; } = new ProductViewModel();
	public string[] supportedImageFormats { get; set; }
	public string[] supportedVideoFormats { get; set; }
	public string[] supportedDocumentFormats { get; set; }
	public string[] allSupportedFormats { get; set; }

	public class RatioSettings
	{
		public string Ratio { get; set; }
		public string CssClass { get; set; }
		public string CssVariable { get; set; }
		public string Fill { get; set; }
	}

	public RatioSettings GetRatioSettings()
	{
		var ratioSettings = new RatioSettings();

		string ratio = Model.Item.GetRawValueString("ImageAspectRatio", "");
		ratio = ratio != "0" ? ratio : "";
		string cssClass = ratio != "" && ratio != "fill" ? " ratio" : "";
		string cssVariable = ratio != "" && ratio != "fill" ? "--bs-aspect-ratio: " + ratio : "";

		ratioSettings.Ratio = ratio;
		ratioSettings.CssClass = cssClass;
		ratioSettings.CssVariable = cssVariable;
		ratioSettings.Fill = ratio == "fill" ? " h-100" : "";

		return ratioSettings;
	}

	public string GetVideoType(string assetValue)
	{
		string type = assetValue.IndexOf("youtu.be", StringComparison.OrdinalIgnoreCase) >= 0 || assetValue.IndexOf("youtube", StringComparison.OrdinalIgnoreCase) >= 0 ? "youtube" : string.Empty;
		type = assetValue.IndexOf("vimeo", StringComparison.OrdinalIgnoreCase) >= 0 ? "vimeo" : type;
		return type;
	}

	public string GetYoutubeScreenDump(string assetValue)
	{
		var regex = new Regex(@"(?:youtube\.com\/.*[\?&]v=|youtu\.be\/|youtube\.com\/embed\/)([\w-]+)(?:\?.*)?");
		Match match = regex.Match(assetValue);
		string videoId = match.Success ? match.Groups[1].Value : string.Empty;
		string youtubeThumbnail = $"https://img.youtube.com/vi/{videoId}/mqdefault.jpg";
		return youtubeThumbnail;
	}

	public string GetFileTypeIcon(string filePath)
	{
		string fileType = Path.GetExtension(filePath).ToLower();
		string fileTypeIconPath = "/Files/Templates/Designs/Swift-v2/Assets/images/FileTypes/";
		var iconMap = new Dictionary<string, string>
		{
			{ ".pdf", $"{fileTypeIconPath}pdf.svg" },
			{ ".docx", $"{fileTypeIconPath}docx.svg" },
			{ ".xlsx", $"{fileTypeIconPath}xlsx.svg" },
			{ ".ppt", $"{fileTypeIconPath}ppt.svg" }
		};
		return iconMap.ContainsKey(fileType) ? iconMap[fileType] : $"/Files/Images/Icons/download.svg";
	}

}

@{
	@* Get the product data *@
	ProductViewModel product = null;
	if (Dynamicweb.Context.Current.Items.Contains("ProductDetails"))
	{
		product = (ProductViewModel)Dynamicweb.Context.Current.Items["ProductDetails"];
	}
}

@if (product is object)
{
	@* Supported formats *@
	supportedImageFormats = new string[] { ".jpg", ".jpeg", ".webp", ".png", ".gif", ".bmp", ".tiff" };
	supportedVideoFormats = new string[] { "youtu.be", "youtube", "vimeo", ".mp4", ".webm" };
	supportedDocumentFormats = new string[] { ".pdf", ".docx", ".xlsx", ".ppt", ".pptx", ".igs", ".ipt", ".sat", ".stp", ".dwg", ".dxf", ".dwf" };

	allSupportedFormats = supportedImageFormats.Concat(supportedVideoFormats).Concat(supportedDocumentFormats).ToArray();

	@* Collect the assets *@
	var selectedAssetCategories = Model.Item.GetList("ImageAssets")?.GetRawValue().OfType<string>();
	bool includeImagePatternImages = Model.Item.GetBoolean("ImagePatternImages");

	@* Needed image data collection to support both DefaultImage, ImagePatterns and Image Assets *@
	string defaultImage = product.DefaultImage != null ? product.DefaultImage.Value : "";
	IEnumerable<MediaViewModel> assetsImages = product.AssetCategories.Where(x => selectedAssetCategories.Contains(x.SystemName)).SelectMany(x => x.Assets);
	assetsImages = assetsImages.OrderByDescending(x => x.Value.Equals(defaultImage));
	IEnumerable<MediaViewModel> assetsList = new MediaViewModel[] { };

	assetsList = assetsList.Union(assetsImages);
	assetsList = includeImagePatternImages ? assetsList.Union(product.ImagePatternImages) : assetsList;
	assetsList = includeImagePatternImages && assetsList.Count() == 0 ? assetsList.Append(product.DefaultImage) : assetsList;

	bool defaultImageFallback = Model.Item.GetBoolean("DefaultImageFallback");
	bool showOnlyPrimaryImage = Model.Item.GetBoolean("ShowOnlyPrimaryImage");

	int totalAssets = 0;
	if (showOnlyPrimaryImage == false) {
		foreach (MediaViewModel asset in assetsList) {
			var assetValue = asset?.Value; 
			if (string.IsNullOrWhiteSpace(assetValue)) continue;
			
			foreach (string format in allSupportedFormats) {
				if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0) {
					totalAssets++;
				}
			}
		}
	}

	if ((totalAssets == 0 && product.DefaultImage != null && selectedAssetCategories.Count() == 0) || (showOnlyPrimaryImage == true && product.DefaultImage != null))
	{
		assetsList = new List<MediaViewModel>(){ product.DefaultImage };
		totalAssets = 1;
	}

	int videoNumber = 0;

	@* Layout settings *@
	bool hideThumbnails = Model.Item.GetBoolean("HideThumbnails");

	string iconPath = "/Files/Images/Icons/";
	int modalVideoNumber = 0;

	@* Get assets from selected categories or get all assets *@

	if (totalAssets != 0 && assetsList.Any())
	{
		<div class="item_@Model.Item.SystemName.ToLower()" data-dw-colorscheme="@Model.ColorScheme?.Id">
			@if (!string.IsNullOrEmpty(Model.Item.GetString("Title")) && !Model.Item.GetBoolean("HideTitle"))
			{
				string titleFontSize = Model.Item.GetRawValueString("TitleFontSize", "h3");

				<h3 class="@titleFontSize mb-3">
					@Model.Item.GetString("Title")
				</h3>
			}

			<div class="table-responsive">
				<table class="table table-hover align-middle mb-0" style="table-layout: fixed;">
					<thead>
						<tr>
							@if (!hideThumbnails)
							{
								<th style="width:60px">&nbsp;</th>
							}
							<th>@Translate("Name")</th>
							<th class="text-end d-none d-lg-table-cell">@Translate("Download")</th>
							<th class="text-end" style="width:100px">@Translate("File type")</th>
						</tr>
					</thead>
					<tbody class="border-top-0">
						@foreach (MediaViewModel asset in assetsList)
						{
							var assetValue = asset.Value;
							string assetName = !string.IsNullOrEmpty(asset.DisplayName) ? asset.DisplayName : asset.Value.Substring(asset.Value.LastIndexOf('/') + 1);

							bool isVideo = false;
							foreach (string format in supportedVideoFormats)
							{ //Videos
								if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
								{
									isVideo = true;
								}
							}

							if (!isVideo)
							{
								if (assetValue.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase))
								{
									string filePath = Dynamicweb.Context.Current.Server.MapPath(assetValue);
									long fileSize = 0;

									if (File.Exists(filePath))
									{
										fileSize = new System.IO.FileInfo(filePath) != null ? new System.IO.FileInfo(filePath).Length / 1024 : 0;

										foreach (string format in allSupportedFormats)
										{
											if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
											{
												<tr>
													@if (!hideThumbnails)
													{
														<td class="px-0">
															@foreach (string imageFormat in supportedImageFormats)
															{ //Images
																if (assetValue.IndexOf(imageFormat, StringComparison.OrdinalIgnoreCase) >= 0)
																{
																	string productName = product.Name;
																	productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
																	string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
																	string imageLinkPath = imagePath;
																	imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
																	imagePath = !imageLinkPath.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? asset.Value : imagePath;

																	string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

																	RatioSettings ratioSettings = GetRatioSettings();

																	<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download>
																		<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																			<img loading="lazy" src="@imagePath" class="mw-100 mh-100" alt="@productName" @assetTitle itemprop="image">
																		</div>
																	</a>
																}
															}
															@foreach (string videoFormat in supportedVideoFormats)
															{ //Videos
																if (assetValue.IndexOf(videoFormat, StringComparison.OrdinalIgnoreCase) >= 0)
																{
																	var video = asset.GetVideoViewModel();
																	string productName = product.Name;
																	productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
																	string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

																	RatioSettings ratioSettings = GetRatioSettings();

																	string type = GetVideoType(asset.Value);
																	string videoScreendumpPath = type == "youtube" ? GetYoutubeScreenDump(asset.Value) : string.Empty;
																	string videoJsClass = type == "vimeo" ? "js-vimeo-video-thumbnail" : string.Empty;

																	<div class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)">
																		<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																			<div class="icon-2 position-absolute" style="z-index: 1">@ReadFile(iconPath + "play-circle.svg")</div>
																			@if (video.IsExternalLink())
																			{
																				<img src="@videoScreendumpPath" loading="lazy" decoding="async" alt="@productName" @assetTitle class="@videoJsClass mw-100 mh-100" data-asset-value="@asset.Value" style="object-fit: cover;">
																			}
																			else
																			{
																				<video preload="auto" class="h-100 w-100" style="object-fit: contain;">
																					<source src="@(asset.Value)#t=0.001" type="@video.GetVideoType()">
																				</video>
																			}
																		</div>
																	</div>
																}
															}
															@foreach (string documentFormat in supportedDocumentFormats)
															{ //Documents
																if (assetValue.IndexOf(documentFormat, StringComparison.OrdinalIgnoreCase) >= 0)
																{
																	string productName = product.Name;
																	productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
																	string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
																	string imageLinkPath = imagePath;
																	imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
																	string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";
																	string fileTypeIcon = GetFileTypeIcon(asset.Value);

																	RatioSettings ratioSettings = GetRatioSettings();

																	<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download alt="@productName">
																		<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																			<div class="icon-5 position-absolute" style="z-index: 1">@ReadFile(fileTypeIcon)</div>
																		</div>
																	</a>
																}
															}
														</td>

													}
													<td>
														<a href="@assetValue" class="text-decoration-none text-break" download="@assetName" title="@assetName">
															@assetName
														</a>
													</td>
													<td class="text-end d-none d-lg-table-cell">
														<a href="@assetValue" class="text-decoration-none" download="@assetName" title="@assetName">
															@fileSize KB <div class="icon-2" style="z-index: 1">@ReadFile(iconPath + "download.svg")</div>
														</a>
													</td>
													<td class="text-end">@format</td>
												</tr>
											}
										}
									}
								}
								else
								{
									<tr>
										@if (!hideThumbnails)
										{
											<td class="px-0">
												@foreach (string format in supportedImageFormats)
												{ //Images
													if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
													{
														string productName = product.Name;
														productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
														string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
														string imageLinkPath = imagePath;
														imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
														imagePath = !imageLinkPath.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? asset.Value : imagePath;

														string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

														RatioSettings ratioSettings = GetRatioSettings();

														<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download>
															<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																<img loading="lazy" src="@imagePath" class="mw-100 mh-100" alt="@productName" @assetTitle itemprop="image">
															</div>
														</a>
													}
												}
												@foreach (string format in supportedVideoFormats)
												{ //Videos
													if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
													{
														var video = asset.GetVideoViewModel();
														string type = GetVideoType(asset.Value);
														string videoScreendumpPath = type == "youtube" ? GetYoutubeScreenDump(asset.Value) : string.Empty;
														string videoJsClass = type == "vimeo" ? "js-vimeo-video-thumbnail" : string.Empty;


														string productName = product.Name;
														productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
														string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

														RatioSettings ratioSettings = GetRatioSettings();

														<div class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)">
															<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																<div class="icon-2 position-absolute" style="z-index: 1">@ReadFile(iconPath + "play-circle.svg")</div>
																@if (video.IsExternalLink())
																{
																	<img src="@videoScreendumpPath" loading="lazy" decoding="async" alt="@productName" @assetTitle class="@videoJsClass mw-100 mh-100" data-asset-value="@asset.Value" style="object-fit: cover;">
																}
																else
																{
																	<video preload="auto" class="h-100 w-100" style="object-fit: contain;">
																		<source src="@(asset.Value)#t=0.001" type="@video.GetVideoType()">
																	</video>
																}
															</div>
														</div>
													}
												}
												@foreach (string format in supportedDocumentFormats)
												{ //Documents
													if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
													{
														string productName = product.Name;
														productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
														string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
														string imageLinkPath = imagePath;
														imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
														string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";
														string fileTypeIcon = GetFileTypeIcon(asset.Value);

														RatioSettings ratioSettings = GetRatioSettings();

														<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download alt="@productName">
															<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
																<div class="icon-5 position-absolute" style="z-index: 1">@ReadFile(fileTypeIcon)</div>
															</div>
														</a>
													}
												}
											</td>
										}
										<td>
											<a href="@assetValue" class="text-decoration-none text-break" download="@assetName" title="@assetName">
												@assetName
											</a>
										</td>
										<td>&nbsp;</td>
										<td>&nbsp;</td>
									</tr>
								}
							}
							else
							{
								string videoType = asset.Value.IndexOf("youtu.be", StringComparison.OrdinalIgnoreCase) >= 0 || asset.Value.IndexOf("youtube", StringComparison.OrdinalIgnoreCase) >= 0 ? "Youtube" : "";
								videoType = asset.Value.IndexOf("vimeo", StringComparison.OrdinalIgnoreCase) >= 0 ? "Vimeo" : videoType;
								videoType = videoType == "" ? Path.GetExtension(asset.Value).ToLower() : videoType;

								<tr data-bs-toggle="modal" data-bs-target="#modal_@(Model.ID)_@videoNumber" style="cursor: pointer">
									@if (!hideThumbnails)
									{
										<td class="px-0">
											@foreach (string format in supportedImageFormats)
											{ //Images
												if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
												{
													string productName = product.Name;
													productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
													string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
													string imageLinkPath = imagePath;
													imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
													imagePath = !imageLinkPath.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? asset.Value : imagePath;

													string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

													RatioSettings ratioSettings = GetRatioSettings();

													<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download>
														<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
															<img loading="lazy" src="@imagePath" class="mw-100 mh-100" alt="@productName" @assetTitle itemprop="image">
														</div>
													</a>
												}
											}
											@foreach (string format in supportedVideoFormats)
											{ //Videos
												if (assetValue.IndexOf(format, StringComparison.OrdinalIgnoreCase) >= 0)
												{
													var video = asset.GetVideoViewModel();
													string type = GetVideoType(asset.Value);
													string videoScreendumpPath = type == "youtube" ? GetYoutubeScreenDump(asset.Value) : string.Empty;
													string videoJsClass = type == "vimeo" ? "js-vimeo-video-thumbnail" : string.Empty;

													string productName = product.Name;
													productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
													string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";

													RatioSettings ratioSettings = GetRatioSettings();

													<div class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)">
														<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
															<div class="icon-2 position-absolute" style="z-index: 1">@ReadFile(iconPath + "play-circle.svg")</div>
															@if (video.IsExternalLink())
															{
																<img src="@videoScreendumpPath" loading="lazy" decoding="async" alt="@productName" @assetTitle class="@videoJsClass mw-100 mh-100" data-asset-value="@asset.Value" style="object-fit: cover;">
															}
															else
															{
																<video preload="auto" class="h-100 w-100" style="object-fit: contain;">
																	<source src="@(asset.Value)#t=0.001" type="@video.GetVideoType()">
																</video>
															}
														</div>
													</div>
												}
											}
											@foreach (string documentFormat in supportedDocumentFormats)
											{ //Documents
												if (assetValue.IndexOf(documentFormat, StringComparison.OrdinalIgnoreCase) >= 0)
												{
													string productName = product.Name;
													productName += !string.IsNullOrEmpty(asset.Keywords) ? " " + asset.Keywords : "";
													string imagePath = !string.IsNullOrEmpty(asset.Value) ? asset.Value : product.DefaultImage.Value;
													string imageLinkPath = imagePath;
													imagePath = $"/Admin/Public/GetImage.ashx?image={imagePath}&width=60&format=webp";
													string assetTitle = !string.IsNullOrEmpty(asset.DisplayName) ? "title=\"" + asset.DisplayName + "\"" : "";
													string fileTypeIcon = GetFileTypeIcon(asset.Value);

													RatioSettings ratioSettings = GetRatioSettings();

													<a href="@imageLinkPath" class="d-block @(ratioSettings.CssClass)@(ratioSettings.Fill)" style="@(ratioSettings.CssVariable)" download alt="@productName">
														<div class="d-flex align-items-center justify-content-center overflow-hidden h-100">
															<div class="icon-5 position-absolute" style="z-index: 1">@ReadFile(fileTypeIcon)</div>
														</div>
													</a>
												}
											}
										</td>
									}
									<td>
										@assetName
									</td>
									<td class="d-none d-lg-table-cell">&nbsp;</td>
									<td align="right">@videoType</td>
								</tr>

								videoNumber++;
							}
						}
					</tbody>
				</table>
			</div>

			@foreach (MediaViewModel asset in assetsList)
			{
				var assetName = asset.Value.ToLower();
				foreach (string videoFormat in supportedVideoFormats)
				{ //Videos
					if (assetName.IndexOf(videoFormat, StringComparison.OrdinalIgnoreCase) >= 0)
					{
						<div class="modal fade js-video-modal" id="modal_@(Model.ID)_@modalVideoNumber" tabindex="-1" aria-labelledby="productDetailsTableModalTitle_@(Model.ID)_@modalVideoNumber" aria-hidden="true">
							<div class="modal-dialog modal-dialog-centered modal-xl">
								<div class="modal-content">
									<div class="modal-header visually-hidden">
										<h5 class="modal-title" id="productDetailsTableModalTitle_@(Model.ID)_@modalVideoNumber">@product.Title</h5>
										<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
									</div>
									<div class="modal-body p-2 p-lg-3 h-100">
										@RenderPartial("Components/VideoPlayer.cshtml", asset.GetVideoViewModel())
									</div>
								</div>
							</div>
						</div>

						modalVideoNumber++;
					}
				}
			}
		</div>
	}
	else if (Pageview.IsVisualEditorMode)
	{
		<div class="h-100" data-dw-colorscheme="@Model.ColorScheme?.Id">
			<div class="alert alert-dark m-0">
				@Translate("The media table will be shown here, if any")
			</div>
		</div>
	}
}
else if (Pageview.IsVisualEditorMode)
{
	<div class="alert alert-dark m-0">@Translate("No products available")</div>
}