@using hassio_onedrive_backup.Contracts;
@using hassio_onedrive_backup.Graph;
@using hassio_onedrive_backup.Hass;
@using hassio_onedrive_backup;
@inject IJSRuntime JS
@inject AddonOptions AddonOptions
@inject HassOnedriveEntityState HassOnedriveEntityState
@inject HassOnedriveFreeSpaceEntityState HassOnedriveFreeSpaceEntityState
@inject HassOnedriveFileSyncEntityState HassOnedriveFileSyncEntityState
@inject Orchestrator Orchestrator
@inject IGraphHelper GraphHelper

<div class="card text-white bg-light mb-3 w-100" style="min-width: 16rem">
	<div class="card-header text-dark">
		<div class="row">
			<div class="col d-flex align-items-center">
				Summary <span class="badge rounded-pill m-1 @SummaryBadgeColor">@SummaryBadgeText</span>
				@if (HassOnedriveEntityState.State == HassOnedriveEntityState.BackupState.Syncing)
				{
					<div class="spinner-border spinner-border-sm text-primary" role="status">
						<span class="visually-hidden">Loading...</span>
					</div>
				}
			</div>
			@if (GraphHelper.IsAuthenticated == true)
			{
				<div class="col text-end">
@*					<span class="oi oi-data-transfer-upload"></span>
					<span class="card-text">@UploadSpeed</span>
*@					<button type="button" @onclick="RefreshData" class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-title="Refresh Backups Data" disabled="@refreshingData">
						<span class="oi oi-reload @(refreshingData ? "refreshing" : string.Empty)" aria-hidden="true"></span>
					</button>

					<button type="button" @onclick="TriggerBackup" class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-title="Trigger a backup now" disabled="@onDemandBackup">
						<span class="card-text">Trigger Backup</span>
						@if (onDemandBackup)
						{
							<span class="spinner-border spinner-border-sm mx-1" role="status" aria-hidden="true"></span>
						}
					</button>
				</div>
			}
		</div>
	</div>
	<div class="card-body bg-light text-body">
		<div class="row">
			<div class="col">
				<span class="card-text">OneDrive Storage</span>
			</div>
			<div class="col">
				@if (HassOnedriveFreeSpaceEntityState.FreeSpaceGB == null)
				{
					<div class="progress">
						<div class="progress-bar progress-bar-striped progress-bar-animated bg-secondary" role="progressbar" style="width: 100%">Initializing</div>
					</div>
				}
				else
				{
					<div class="progress">
						<div class="progress-bar @FreeSpaceColor" role="progressbar" style="width: @(OneDriveUsedSpacePercentage)%" aria-valuenow="@OneDriveUsedSpacePercentage" data-bs-toggle="tooltip" title=@(OneDriveUsedSpace.ToString("N2") + " GB / " + (HassOnedriveFreeSpaceEntityState.FreeSpaceGB ?? 0).ToString("N2") + " GB" ) aria-valuemin="0" aria-valuemax="100">Used: @(OneDriveUsedSpacePercentage)%</div>
					</div>
				}
			</div>
		</div>
		<div class="row">
			<div class="col">
				<span class="card-text">Local Backups</span>
			</div>
			<div class="col">
				<div class="progress">
					<div class="progress-bar bg-primary" role="progressbar" style="width: @(LocalBackupsPercentage)%" aria-valuenow="@LocalBackupsPercentage" aria-valuemin="0" aria-valuemax="@AddonOptions.MaxLocalBackups">@HassOnedriveEntityState.BackupsInHomeAssistant / @AddonOptions.MaxLocalBackups</div>
					@*<div class="progress-bar bg-secondary" role="progressbar" style="width: @(100 - LocalBackupsPercentage)%" aria-valuenow="@(100 - LocalBackupsPercentage)" aria-valuemin="0" aria-valuemax="@AddonOptions.MaxLocalBackups"></div>*@
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<span class="card-text">OneDrive Backups</span>
			</div>
			<div class="col">
				<div class="progress">
					<div class="progress-bar bg-primary" role="progressbar" style="width: @(OneDriveBackupsPercentage)%" aria-valuenow="@OneDriveBackupsPercentage" aria-valuemin="0" aria-valuemax="@AddonOptions.MaxOnedriveBackups">@HassOnedriveEntityState.BackupsInOnedrive / @AddonOptions.MaxOnedriveBackups</div>
					@*<div class="progress-bar bg-secondary" role="progressbar" style="width: @(100 - OneDriveBackupsPercentage)%" aria-valuenow="@(100 - OneDriveBackupsPercentage)" aria-valuemin="0" aria-valuemax="@AddonOptions.MaxOnedriveBackups"></div>*@
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col">
				<span class="card-text">Last Backup Date</span>
			</div>
			<div class="col">
				@if (LastBackupDate == null)
				{
					<span class="card-text">None</span>
				}
				else
				{
					<span class="card-text">@LastBackupDate</span>
				}
			</div>
		</div>
		<div class="row">
			<div class="col">
				<span class="card-text">Backup Upload Progress</span>
			</div>
			<div class="col">
				@if (HassOnedriveEntityState.UploadPercentage == null)
				{
					<span class="card-text">N/A</span>
				}
				else
				{
					<div class="progress">
						<div class="progress-bar progress-bar-animated bg-primary" role="progressbar" style="width: @(HassOnedriveEntityState.UploadPercentage)%">@BackupUploadSpeed</div>
					</div>
				}
			</div>
		</div>
		@if (AddonOptions.FileSyncEnabled)
		{
			<div class="row">
				<div class="col">
					<span class="card-text">File Sync Upload Progress</span>
				</div>
				<div class="col">
					@if (HassOnedriveFileSyncEntityState.State != HassOnedriveFileSyncEntityState.FileState.Syncing)
					{
						<span class="card-text">N/A</span>
					}
					else
					{
						<div class="progress">
							<div class="progress-bar progress-bar-animated bg-primary" role="progressbar" style="width: @(HassOnedriveFileSyncEntityState.UploadPercentage)%">@(FileUploadSpeed)</div>
						</div>
					}
				</div>
			</div>
		}
	</div>
</div>

@code {
	private bool onDemandBackup = false;

	private bool refreshingData = false;

	private int OneDriveUsedSpacePercentage => (int)((OneDriveUsedSpace / (HassOnedriveFreeSpaceEntityState.TotalSpaceGB ?? 1)) * 100);

	private int LocalBackupsPercentage => (int)((HassOnedriveEntityState.BackupsInHomeAssistant / (double)AddonOptions.MaxLocalBackups) * 100);

	private int OneDriveBackupsPercentage => (int)((HassOnedriveEntityState.BackupsInOnedrive / (double)AddonOptions.MaxOnedriveBackups) * 100);

	private string BackupUploadSpeed => ViewHelpers.GetSpeedDisplayText(HassOnedriveEntityState.UploadSpeed);

	private string FileUploadSpeed => ViewHelpers.GetSpeedDisplayText(HassOnedriveFileSyncEntityState.UploadSpeed);

	private double OneDriveUsedSpace => ((HassOnedriveFreeSpaceEntityState.TotalSpaceGB ?? 0) - (HassOnedriveFreeSpaceEntityState.FreeSpaceGB ?? 0));

	private DateTime? LastBackupDate => HassOnedriveEntityState.LastLocalBackupDate > HassOnedriveEntityState.LastOnedriveBackupDate ? HassOnedriveEntityState.LastLocalBackupDate : HassOnedriveEntityState.LastOnedriveBackupDate;

	private string FreeSpaceColor => OneDriveUsedSpacePercentage > 90 ? "bg-danger" : "bg-primary";

	private string SummaryBadgeColor
	{
		get
		{
			switch (HassOnedriveEntityState.State)
			{
				case HassOnedriveEntityState.BackupState.Stale:
					return "bg-warning";
				case HassOnedriveEntityState.BackupState.Backed_Up:
					return "bg-success";
				case HassOnedriveEntityState.BackupState.Backed_Up_Local:
					return "bg-secondary";
				case HassOnedriveEntityState.BackupState.Backed_Up_Onedrive:
					return "bg-primary";
				case HassOnedriveEntityState.BackupState.Syncing:
					return "bg-dark";
				default:
					return "bg-dark";
			}
		}
	}

	private string SummaryBadgeText
	{
		get
		{
			switch (HassOnedriveEntityState.State)
			{
				case HassOnedriveEntityState.BackupState.Stale:
					return "Stale";
				case HassOnedriveEntityState.BackupState.Backed_Up:
					return "Backed Up";
				case HassOnedriveEntityState.BackupState.Backed_Up_Local:
					return "Backed Up Local";
				case HassOnedriveEntityState.BackupState.Backed_Up_Onedrive:
					return "Backed Up OneDrive";
				case HassOnedriveEntityState.BackupState.Syncing:
					return "Syncing";
				default:
					return "";
			}
		}
	}

	protected override void OnInitialized()
	{
		base.OnInitialized();
		HassOnedriveFreeSpaceEntityState.PropertyChanged += TriggerStateChanged;
		HassOnedriveEntityState.PropertyChanged += TriggerStateChanged;
		HassOnedriveFileSyncEntityState.PropertyChanged += TriggerStateChanged;
		Orchestrator.BackupManager.OneDriveBackupsUpdated += TriggerStateChanged;
		Orchestrator.BackupManager.LocalBackupsUpdated += TriggerStateChanged;
	}

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		if (firstRender)
		{
			// await JS.InvokeVoidAsync("addTooltips");
		}
	}


	private async void TriggerBackup()
	{
		onDemandBackup = true;
		bool ret = await Orchestrator.BackupManager.CreateLocalBackup();
		onDemandBackup = false;
		TriggerStateChanged();
	}

	private async void RefreshData()
	{
		refreshingData = true;
		TriggerStateChanged();
		await Orchestrator.BackupManager.RefreshBackupData();
		refreshingData = false;
		TriggerStateChanged();
	}

	private async void TriggerStateChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
	{
		await InvokeAsync(() =>
		{
			StateHasChanged();
		});
	}

	private async void TriggerStateChanged()
	{
		await InvokeAsync(() =>
		{
			StateHasChanged();
		});
	}
}
