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

@{
	ProductViewModel product = null;
	if (Dynamicweb.Context.Current.Items.Contains("ProductDetails"))
	{
		product = (ProductViewModel)Dynamicweb.Context.Current.Items["ProductDetails"];
	} else if (Pageview.IsVisualEditorMode) {
		product = new ProductViewModel();
		product.StockLevel = 10;
		product.StockStatus = Translate("In stock");
		product.StockDeliveryText = Translate("Delivery next week");
	}

	bool isErpConnectionDown = !Dynamicweb.Core.Converter.ToBoolean(Dynamicweb.Context.Current.Items["IsWebServiceConnectionAvailable"]);
	bool hideStock = Model.Item.GetBoolean("HideStockState");
}

@if (product is object && product.ProductType == Dynamicweb.Ecommerce.Products.ProductType.Stock && !hideStock)
{
	
	string horizontalAlign = Model.Item.GetRawValueString("HorizontalAlignment", "");
	horizontalAlign = horizontalAlign == "center" ? "text-center" : horizontalAlign;
	horizontalAlign = horizontalAlign == "end" ? "text-end" : horizontalAlign;
	bool hasExpectedDelivery = product.ExpectedDelivery != null && product.ExpectedDelivery > DateTime.Now;
	string expectedDeliveryDate = product.ExpectedDelivery?.ToShortDateString() ?? "";

	if (!product.NeverOutOfstock)
	{
		string deliveryLabel = !string.IsNullOrEmpty(product.StockDeliveryText) ? $"{product.StockDeliveryText}" : "";
		deliveryLabel += !string.IsNullOrEmpty(product.StockDeliveryValue) ? $" {product.StockDeliveryValue}" : "";

		string firstUnitId = product?.UnitOptions?.FirstOrDefault() != null ? product.UnitOptions.FirstOrDefault().Id : "";
		string defaultUnitId = !string.IsNullOrEmpty(product.DefaultUnitId) ? product.DefaultUnitId : firstUnitId;
		string unitId = !string.IsNullOrEmpty(Dynamicweb.Context.Current.Request.Form.Get("UnitId")) ? Dynamicweb.Context.Current.Request.Form.Get("UnitId") : defaultUnitId;

		double? currentStockLevel = product.StockLevel;

		string stockStateLabel = currentStockLevel > 0 ? Translate("In stock") : Translate("Out of stock");
		stockStateLabel = !string.IsNullOrEmpty(product.StockStatus) ? product.StockStatus : stockStateLabel;

		string stockStateCss = currentStockLevel > 0 ? "text-success" : "text-danger";
		string stockStateIconCss = currentStockLevel > 0 ? "bg-success" : "bg-danger";

		<div class="js-stock-state @horizontalAlign item_@Model.Item.SystemName.ToLower()">
			<div class="small">
				@if (!Model.Item.GetBoolean("HideInventory") && currentStockLevel > 0)
				{
					<span class="@stockStateCss js-text-stock">@currentStockLevel</span> 
				}
				<span class="@stockStateCss">@stockStateLabel</span>
				@if (!string.IsNullOrEmpty(deliveryLabel))
				{
					<span class="opacity-75">@deliveryLabel</span>
				}
			</div>

			@if (hasExpectedDelivery)
			{
				<div>
					<span>@Translate("Expected in stock"): </span>
					<span>@expectedDeliveryDate</span>
				</div>
			}
		</div>
	}
}
