@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Core.Interfaces
@using AyCode.Core.Loggers;
@using AyCode.Utils.Extensions
@using FruitBank.Common.Dtos
@using FruitBankHybrid.Shared.Components.Grids.ShippingItems
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Services.Loggers;
@using FruitBankHybrid.Shared.Services.SignalRs

@inject IEnumerable<IAcLogWriterClientBase> LogWriters
@inject FruitBankSignalRClient FruitBankSignalRClient

<MgGridWithInfoPanel ShowInfoPanel="@IsMasterGrid">
	<GridContent>
		<GridStockQuantityHistoryDtoBase @ref="Grid" ContextIds="ContextIds" ParentDataItem="ParentDataItem" DataSource="StockQuantityHistoryDtos"
										 AutoSaveLayoutName="GridStockQuantityHistoryDto" SignalRClient="FruitBankSignalRClient" Logger="_logger"
										 CssClass="@GridCss" ValidationEnabled="false">
			<Columns>
				<DxGridDataColumn FieldName="Id" Width="125" SortIndex="0" SortOrder="GridColumnSortOrder.Descending" ReadOnly="true" />

				<DxGridDataColumn FieldName="ProductId" ReadOnly="true" Visible="@IsMasterGrid">
					<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="QuantityAdjustment" Width="135" Caption="Adj. Quantity" ReadOnly="true" />
				<DxGridDataColumn FieldName="StockQuantity" Width="135" ReadOnly="true" />

				<DxGridDataColumn FieldName="StockQuantityHistoryId" Width="135" Caption="SqhId" ReadOnly="true" Visible="false" />
				<DxGridDataColumn FieldName="NetWeightAdjustment" Width="135" Caption="Adj. NetWeight(kg)" ReadOnly="true" />
				<DxGridDataColumn FieldName="NetWeight" Width="135" Caption="Net Weight(kg)" ReadOnly="true" />

				<DxGridDataColumn FieldName="Message" ReadOnly="true" />
				<DxGridDataColumn FieldName="IsInconsistent" Width="105" Caption="Inconsistent" ReadOnly="true" />
				<DxGridDataColumn FieldName="CombinationId" Width="125" ReadOnly="true" Visible="false" />
				<DxGridDataColumn FieldName="WarehouseId" Width="125" ReadOnly="true" Visible="false" />

				<DxGridDataColumn FieldName="CreatedOnUtc" Width="150" Caption="Created" ReadOnly="true" DisplayFormat="g" />
			</Columns>
			<ToolbarTemplate>
				@if (IsMasterGrid)
				{
					<MgGridToolbarTemplate Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)" EnableDelete="false" EnableEdit="false" EnableNew="false" />
				}
			</ToolbarTemplate>
			@* <GroupSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="MeasuredQuantity"
						   FooterColumnName="Quantity" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="MeasuredGrossWeight"
						   FooterColumnName="GrossWeight" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="MeasuredNetWeight"
						   FooterColumnName="NetWeight" />
	</GroupSummary> *@
		</GridStockQuantityHistoryDtoBase>
	</GridContent>
</MgGridWithInfoPanel>

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

	[Parameter] public object[]? ContextIds { get; set; }
	[Parameter] public IId<int>? ParentDataItem { get; set; }

	[Parameter] public IEnumerable<ProductDto>? ProductDtos { get; set; }
	[Parameter] public List<StockQuantityHistoryDto>? StockQuantityHistoryDtos { get; set; }

	public bool IsMasterGrid => ParentDataItem == null;
	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	public GridStockQuantityHistoryDtoBase Grid { get; set; }
	private LoggerClient<GridStockQuantityHistoryDtoTemplate> _logger = null!;

	protected override async Task OnInitializedAsync()
	{
		_logger = new LoggerClient<GridStockQuantityHistoryDtoTemplate>(LogWriters.ToArray());

		await ReloadDataFromDb(false);
	}

	public async Task ReloadDataFromDb(bool forceReload = false)
	{
		if (!IsMasterGrid) return;

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

		if (Grid == null || !forceReload) return;

		using (await ObjectLock.GetSemaphore<StockQuantityHistoryDto>().UseWaitAsync())
			if (forceReload) await Grid.ReloadDataSourceAsync();

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