@using System.Collections.ObjectModel
@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Core.Helpers
@using AyCode.Core.Loggers
@using AyCode.Utils.Extensions
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@using FruitBankHybrid.Shared.Components.Grids.Shippings
@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>
		<GridCargoPartnerBase @ref="Grid"
							  DataSource="CargoPartners"
							  AutoSaveLayoutName="GridCargoPartner"
							  SignalRClient="FruitBankSignalRClient"
							  Logger="_logger"
							  CssClass="@GridCss"
							  ValidationEnabled="false"
							  OnGridFocusedRowChanged="Grid_FocusedRowChanged">
			<Columns>
				<DxGridDataColumn FieldName="Id" SortIndex="0" SortOrder="GridColumnSortOrder.Descending" ReadOnly="true" />

				<DxGridDataColumn FieldName="Name" />
				<DxGridDataColumn FieldName="TaxId" />
				<DxGridDataColumn FieldName="CertificationNumber" />
				<DxGridDataColumn FieldName="@nameof(CargoPartner.Currency)" />
				<DxGridDataColumn FieldName="@nameof(CargoPartner.CountryCode)" />
				<DxGridDataColumn FieldName="PostalCode" />
				<DxGridDataColumn FieldName="@nameof(CargoPartner.Country)" />
				<DxGridDataColumn FieldName="State" />
				<DxGridDataColumn FieldName="County" />
				<DxGridDataColumn FieldName="City" />
				<DxGridDataColumn FieldName="Street" />

				<DxGridDataColumn FieldName="Created" ReadOnly="true" />
				<DxGridDataColumn FieldName="Modified" ReadOnly="true" />
				<DxGridCommandColumn Visible="!IsMasterGrid" Width="120"></DxGridCommandColumn>
			</Columns>
			<DetailRowTemplate>
				@if (IsMasterGrid)
				{
					var cargoPartner = ((CargoPartner)context.DataItem);
					var shippings = new AcObservableCollection<Shipping>(); //cargoPartner?.Shippings ?? [];
					var cargoTrucks = cargoPartner?.CargoTrucks ?? [];

					<DxTabs>
						<DxTabPage Text="Kamionok">
							@{
								var observableCargoTruck = new AcObservableCollection<CargoTruck>(cargoTrucks);
								<GridCargoTruck ParentDataItem="@cargoPartner" CargoTrucks="@observableCargoTruck"></GridCargoTruck>
							}
						</DxTabPage>

@* 						<DxTabPage Text="Szállítmányok">
							@{
								//var observableShippings = new AcObservableCollection<Shipping>(shippings);
								<GridShipping Shippings="@shippings" IsMasterGrid="false" />
							}
						</DxTabPage>
 *@					</DxTabs>
				}
			</DetailRowTemplate>
			<ToolbarTemplate>
				@if (IsMasterGrid)
				{
					<MgGridToolbarTemplate Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)" />
				}
			</ToolbarTemplate>
		</GridCargoPartnerBase>
	</GridContent>
</MgGridWithInfoPanel>

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

	[Parameter] public bool IsMasterGrid { get; set; } = false;
	[Parameter] public AcObservableCollection<CargoPartner>? CargoPartners { get; set; }
	[Parameter] public AcObservableCollection<Shipping>? Shippings { get; set; }


	const string ExportFileName = "ExportResult";
	string GridSearchText = "";
	bool EditItemsEnabled { get; set; }
	int FocusedRowVisibleIndex { get; set; }
	public GridCargoPartnerBase Grid { get; set; }
	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	private int _activeTabIndex;
	private LoggerClient<GridCargoPartner> _logger;

	protected override async Task OnInitializedAsync()
	{
		_logger = new LoggerClient<GridCargoPartner>(LogWriters.ToArray());
		await ReloadDataFromDb(false);
	}

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

		if (Grid == null) return;

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

		if (forceReload) Grid.Reload();
	}

	async Task Grid_FocusedRowChanged(GridFocusedRowChangedEventArgs args)
	{
		if (Grid == null) return;

		if (Grid.IsEditing() && !Grid.IsEditingNewRow())
			await Grid.SaveChangesAsync();

		FocusedRowVisibleIndex = args.VisibleIndex;
		EditItemsEnabled = true;
	}
}

