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

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

	string anonymousUsersLimitations = Pageview.AreaSettings.GetRawValueString("AnonymousUsers", "");
	bool anonymousUser = Pageview.User == null;
	bool hideAddToCart = anonymousUsersLimitations.Contains("cart") && anonymousUser;
	hideAddToCart = Pageview.IsVisualEditorMode ? false : hideAddToCart;
}

@if (product is object && !hideAddToCart)
{
	string contextCart = Model.Item.GetRawValueString("ContextCart", "");

	string formurl = "/Default.aspx?ID=" + (GetPageIdByNavigationTag("CartService"));
	if (!formurl.Contains("LayoutTemplate"))
	{
		formurl += formurl.Contains("?") ? "&LayoutTemplate=Swift-v2_MiniCart.cshtml" : "?LayoutTemplate=Swift-v2_MiniCart.cshtml";
	}

	string horizontalAlign = Model.Item.GetRawValueString("HorizontalAlignment", "");
	horizontalAlign = horizontalAlign == "center" ? "justify-content-center" : horizontalAlign;
	horizontalAlign = horizontalAlign == "end" ? "justify-content-end" : horizontalAlign;
	horizontalAlign = horizontalAlign == "full" ? "" : horizontalAlign;

	string iconPath = "/Files/Images/Icons/";
	string url = "/Default.aspx?ID=" + (GetPageIdByNavigationTag("CartService"));
	if (!url.Contains("LayoutTemplate"))
	{
		url += url.Contains("?") ? "&LayoutTemplate=Swift-v2_MiniCart.cshtml" : "?LayoutTemplate=Swift-v2_MiniCart.cshtml";
	}

	string cartCommand = "add";
	string buttonStyle = "primary";
	bool inCart = false;

	string fullWidth = Model.Item.GetRawValueString("HorizontalAlignment", "") == "full" ? "w-100" : "";
	string addToCartIcon = Model.Item.GetRawValueString("Icon", iconPath + "download.svg");
	string addToCartLabel = "";

	if (!string.IsNullOrEmpty(contextCart))
	{
		addToCartLabel += !addToCartIcon.Contains("_none") ? "<span class=\"icon-2\">" + ReadFile(addToCartIcon) + "</span>" : "";
		addToCartLabel += !addToCartIcon.Contains("_none") && !Model.Item.GetBoolean("HideButtonText") ? " " : "";

		if (product.IsProductInCart(contextCart))
		{
			addToCartLabel += !Model.Item.GetBoolean("HideButtonText") ? Translate("Remove from download cart") : "";
			cartCommand = "delorderline";
			buttonStyle = "secondary";
			inCart = true;
		}
		else
		{
			addToCartLabel += !Model.Item.GetBoolean("HideButtonText") ? Translate("Add to download cart") : "";
		}

		<div class="d-flex @horizontalAlign @fullWidth item_@Model.Item.SystemName.ToLower()">
			<form method="post" action="@formurl" class="@fullWidth" style="z-index: 1">
				<input type="hidden" name="OrderContext" value="@contextCart">
				<input type="hidden" name="minicartid" value="@contextCart">
				<input type="hidden" name="redirect" value="false">
				<input type="hidden" name="ProductId" value="@product.Id">

				@if (!string.IsNullOrEmpty(product.VariantId))
				{
					<input type="hidden" name="VariantId" value="@product.VariantId">
				}

				<input name="Quantity" value="1" type="hidden">

				<input type="hidden" name="cartcmd" value="@cartCommand">
				<button type="button" class="btn btn-@(buttonStyle) js-add-to-cart-button @fullWidth" data-dw-button="@buttonStyle" onclick="swift.Cart.Update(event); this.addEventListener('updated.swift.cart', updateDownloadCartButton(this))" data-in-cart="@inCart" id="AddToDownloadCartButton@(product.Id)@(product.VariantId.Replace(".", "_"))">

					@if (!Model.Item.GetBoolean("HideButtonText"))
					{
						<span class="text-nowrap d-flex align-items-center justify-content-center gap-2">
							@addToCartLabel
						</span>
					}
					else
					{
						@addToCartLabel
					}
				</button>
			</form>

			<script>
				function debounce(func, wait, immediate) {
					var timeout;
					return function () {
						var context = this, args = arguments;
						var later = function () {
							timeout = null;
							if (!immediate) func.apply(context, args);
						};
						var callNow = immediate && !timeout;
						clearTimeout(timeout);
						timeout = setTimeout(later, wait);
						if (callNow) func.apply(context, args);
					};
				};

				updateDownloadCartButton = debounce(function (clickedButton) {
					var inCart = clickedButton.getAttribute('data-in-cart');

					let parser = new DOMParser();
					const icon = parser.parseFromString(clickedButton.innerHTML, 'text/html').querySelector(".icon-2");

					if (inCart == 'True') {
						const label = icon != null ? icon.outerHTML + " @Translate("Add to download cart")" : "@Translate("Add to download cart")";

						clickedButton.parentNode.querySelector('input[name="cartcmd"]').value = 'add';
						clickedButton.innerHTML = '<span class="text-nowrap">' + label + '</span>';
						clickedButton.classList.add('btn-primary');
						clickedButton.setAttribute("data-dw-button", "primary");
						clickedButton.classList.remove('btn-secondary');
						clickedButton.setAttribute('data-in-cart', 'False');
					} else {
						const label = icon != null ? icon.outerHTML + " @Translate("Remove from download cart")" : "@Translate("Remove from download cart")";

						clickedButton.parentNode.querySelector('input[name="cartcmd"]').value = 'delorderline';
						clickedButton.innerHTML = '<span class="text-nowrap">' + label + '</span>';
						clickedButton.classList.remove('btn-primary');
						clickedButton.classList.add('btn-secondary');
						clickedButton.setAttribute("data-dw-button", "secondary");
						clickedButton.setAttribute('data-in-cart', 'True');
					}
				}, 500);
			</script>
		</div>
	}
	else if (Pageview.IsVisualEditorMode)
	{
		<div class="alert alert-dark m-0">@Translate("Please create and select a context cart")</div>
	}
}
else if (Pageview.IsVisualEditorMode)
{
	<div class="alert alert-dark m-0">@Translate("No products available")</div>
}
