@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Core.Helpers
@using AyCode.Utils.Extensions
@using FruitBank.Common
@using FruitBank.Common.Dtos
@using FruitBank.Common.Models
@using FruitBankHybrid.Shared.Components.Grids.GenericAttributes
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Services.SignalRs

@inject LoggedInModel LoggedInModel;
@inject FruitBankSignalRClient FruitBankSignalRClient

<MgGridBase @ref="Grid" Data="OrderItemDtos" IsMasterGrid="IsMasterGrid"
			PageSize="@(IsMasterGrid ? 20 : 50)" ShowFilterRow="IsMasterGrid" ShowGroupPanel="IsMasterGrid"
			AutoExpandAllGroupRows="false" AutoSaveLayoutName="GridDetailOrderItemDto"
			ColumnResizeMode="GridColumnResizeMode.NextColumn"
			CssClass="@GridCss"
			FilterMenuButtonDisplayMode="@(IsMasterGrid ? GridFilterMenuButtonDisplayMode.Never : GridFilterMenuButtonDisplayMode.Always)">
	<Columns>
		<DxGridDataColumn FieldName="Id" />
		<MgGridDataColumn FieldName="OrderId" UrlLink=@(FruitBankConstClient.BaseUrl + "/Admin/Order/Edit/{OrderId}") />
		<DxGridDataColumn FieldName="@("OrderDto.Customer.Company")" Caption="Company" ReadOnly="true" />
		<DxGridDataColumn FieldName="ProductId">
			<EditSettings>
				<DxComboBoxSettings Data="ProductDtos"
									ValueFieldName="Id"
									TextFieldName="Name"
									DropDownBodyCssClass="dd-body-class"
									ListRenderMode="ListRenderMode.Entire"
									SearchMode="ListSearchMode.AutoSearch"
									SearchFilterCondition="ListSearchFilterCondition.Contains"
									ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto" />
			</EditSettings>
		</DxGridDataColumn>

		@* <DxGridDataColumn FieldName="ProductName" /> *@

		<DxGridDataColumn FieldName="Quantity" />
		<DxGridDataColumn FieldName="NetWeight" />

		<DxGridDataColumn FieldName="IsMeasurable" ReadOnly="true" />
		<DxGridDataColumn FieldName="MeasuringStatus" ReadOnly="true" />
		@* <DxGridDataColumn FieldName="IsMeasured" ReadOnly="true" /> *@

		<DxGridDataColumn FieldName="UnitPriceInclTax" Caption="Egységár (br.)" />
		<DxGridDataColumn FieldName="PriceInclTax" Caption="Végösszeg (br.)" />

		<DxGridDataColumn FieldName="AverageWeight" ReadOnly="true" Visible="false" Caption="AvgWeight" />
		<DxGridDataColumn FieldName="AverageWeightDifference" ReadOnly="true" Visible="false" Caption="AvgWeightDiff" />
		<DxGridDataColumn FieldName="AverageWeightIsValid" ReadOnly="true" Caption="AvgWeightValid" />
		<DxGridDataColumn FieldName="IsAudited" ReadOnly="true" />
		<DxGridDataColumn FieldName="@("OrderDto.CreatedOnUtc")" Caption="Rendelés ideje" ReadOnly="true" DisplayFormat="yyyy.MM.dd hh:mm" />
		<DxGridCommandColumn Visible="!IsMasterGrid" Width="120"></DxGridCommandColumn>
	</Columns>
	<DetailRowTemplate>
		@if (IsMasterGrid && LoggedInModel.IsAdministrator)
		{
			var orderItemDto = ((OrderItemDto)context.DataItem);
			<DxTabs>
				<DxTabPage Text="Mérések">
					@{
						<GridDetailOrderItemPallets OrderItemPallets="orderItemDto.OrderItemPallets" />
					}
				</DxTabPage>
				<DxTabPage Text="Speciális jellemzők" Visible="@LoggedInModel.IsDeveloper">
					@{
						var genericAttributeDtos = new AcObservableCollection<GenericAttributeDto>(orderItemDto.GenericAttributes);
						<GridGenericAttribute ParentDataItem="@orderItemDto" GenericAttributes="@genericAttributeDtos" />
					}
				</DxTabPage>
			</DxTabs>
		}
	</DetailRowTemplate>
	<ToolbarTemplate>
		@if (IsMasterGrid)
		{
			<MgGridToolbarTemplate Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)" />
		}
	</ToolbarTemplate>
	<GroupSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="Quantity"
						   FooterColumnName="Quantity" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="NetWeight"
						   FooterColumnName="NetWeight" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="PriceInclTax"
						   FooterColumnName="PriceInclTax" />
	</GroupSummary>
</MgGridBase>

@code {
	[Inject] public required DatabaseClient Database { get; set; }

	[Parameter] public bool IsMasterGrid { get; set; } = false;
	//[Parameter] public OrderDto? OrderDto { get; set; }
	[Parameter] public List<OrderItemDto>? OrderItemDtos { get; set; }
	[Parameter] public IEnumerable<ProductDto>? ProductDtos { get; set; }

	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	public MgGridBase Grid;

	protected override async Task OnInitializedAsync()
	{
		await ReloadDataFromDb();
	}

	private async Task ReloadDataFromDb(bool forceReload = false)
	{
		LoadingPanelVisibility.Visible = true;

		//using (await ObjectLock.GetSemaphore<ProductDto>().UseWaitAsync())
		{
			if (ProductDtos == null || !ProductDtos.Any() || forceReload) ProductDtos = await Database.ProductDtoTable.LoadDataAsync(!forceReload);
		}

		if (IsMasterGrid)
		{
			using (await ObjectLock.GetSemaphore<OrderItemDto>().UseWaitAsync())
			{
				if (OrderItemDtos == null) OrderItemDtos = await FruitBankSignalRClient.GetAllOrderItemDtos() ?? [];
				else if (OrderItemDtos.Count == 0 || forceReload)
				{
					OrderItemDtos.Clear();
					OrderItemDtos.AddRange(await FruitBankSignalRClient.GetAllOrderItemDtos() ?? []);
				}
			}

			// if (ProductDtos == null || !ProductDtos.Any() || forceReload)
			// {
			// 	//ProductDtos = await Database.ProductDtoTable.LoadDataAsync(!forceReload);

			// 	Database.ProductDtoTable.LoadDataAsync(!forceReload).ContinueWith(x =>
			// 	{
			// 		ProductDtos = x.Result;
			// 	}).Forget();
			// }

			//if (forceReload)
			Grid?.Reload();
		}

		LoadingPanelVisibility.Visible = false;
	}
}