@using hassio_onedrive_backup;
@using hassio_onedrive_backup.Contracts;
@using onedrive_backup.Extensions;
@using onedrive_backup.Hass;
@using onedrive_backup.Models;
@inject Orchestrator Orchestrator;
@inject AddonOptions AddonOptions;
@inject IJSRuntime JS

<div class="card text-white bg-light mb-3 w-100 h-100" style="min-width: 16rem">
    <div class="card-header text-dark">
        <div class="row">
            <div class="col-8">
                @**************Add Badges*****************@
                @if (Backup.Type != null)
                {
                    <span class="badge rounded-pill m-1 @BackupTypeColor" data-bs-toggle="tooltip" data-bs-title="Backup is @Backup.Type">@Backup.Type</span>
                }
                @if (Backup.Location == BackupModel.BackupLocation.OneDrive || Backup.Location == BackupModel.BackupLocation.Both)
                {
                    <span class="badge rounded-pill m-1 bg-primary" data-bs-toggle="tooltip" data-bs-title="Backup is in OneDrive">OneDrive</span>
                }
                @if (Backup.Location == BackupModel.BackupLocation.Local || Backup.Location == BackupModel.BackupLocation.Both)
                {
                    <span class="badge rounded-pill m-1 bg-dark" data-bs-toggle="tooltip" data-bs-title="Backup is in Home Assistant">Local</span>
                }
                @if (Backup.IsProtected)
                {
                    <span class="badge rounded-pill m-1 bg-dark" data-bs-toggle="tooltip" data-bs-title="Backup is password protected">Protected</span>
                }
                @***************@
            </div>
            <div class="col text-end">
                <span class="small">@timeAgoText</span>
            </div>
        </div>
    </div>
    <div class="card-body bg-light text-body">
        <h6 class="card-title">@Backup.DisplayName</h6>
        <h7 class="card-subtitle text-muted">@(Backup.Date)</h7>
        @if (Backup.Size > 0)
        {
            <div class="card-text">@Backup.Size MB</div>
        }
        <div class="collapse" id="details-@Backup.Slug">
            @if (Backup.Folders != null && Backup.Folders.Any())
            {
                <div class="card-text">
                    <p><strong>Folders:</strong>@string.Join(", ", Backup.Folders)</p>
                </div>
            }
        </div>
    </div>
    <div class="card-footer d-flex">

        @*Upload Button*@
        @if (@Backup.Location == BackupModel.BackupLocation.Local)
        {
            <button type="button" @onclick="UploadBackup" class="btn btn-sm m-1 btn-outline-primary" data-bs-toggle="tooltip" data-bs-title="Upload backup to OneDrive" disabled="@uploading">
                @if (uploading)
                {
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    <span class="oi oi-cloud-upload">Uploading @uploadPercent%</span>
                }
                else
                {
                    <span class="oi oi-cloud-upload">Upload</span>
                }
            </button>
        }

        @*Download Button*@
        @if (@Backup.Location == BackupModel.BackupLocation.OneDrive)
        {
            <button type="button" @onclick="DownloadBackup" class="btn btn-sm m-1 btn-outline-primary" data-bs-toggle="tooltip" data-bs-title="Download Backup to Home Assistant" disabled="@downloading">
                @if (downloading)
                {
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    <span class="oi oi-cloud-download">Downloading @downloadPercent%</span>
                }
                else
                {
                    <span class="oi oi-cloud-download">Download</span>
                }
            </button>
        }

        @*Details Button*@
        <button type="button" class="btn btn-sm m-1 btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#details-@Backup.Slug" disabled="@detailsDisabled"><span class="oi oi-expand-down" title="Backup details">Details</span></button>

        @if (transferSpeed > 0)
        {
            <span class="text-end ms-auto my-auto text-dark">@TransferSpeedText</span>
        }
    </div>
</div>


@code {
    private bool uploading = false;
    private bool downloading = false;
    private int uploadPercent = 0;
    private int downloadPercent = 0;
    private int transferSpeed = 0;

    [Parameter]
    public BackupModel Backup { get; set; }

    public string BackupTypeColor => Backup.Type.Equals("full", StringComparison.OrdinalIgnoreCase) ? "bg-info" : "bg-secondary";

    private bool detailsDisabled => (Backup.Addons?.Count() > 0 || Backup.Folders?.Count() > 0) ? false : true;

    private string timeAgoText => CalculateTimeAgoText();

    private string TransferSpeedText => ViewHelpers.GetSpeedDisplayText(transferSpeed / 1000);

    private string CalculateTimeAgoText()
    {
        TimeSpan timeAgo = DateTimeHelper.Instance.Now - Backup.Date;
        if (timeAgo.TotalDays > 1)
        {
            return $"{timeAgo.Days} days ago";
        }
        else if (timeAgo.TotalHours > 1)
        {
            return $"{timeAgo.Hours} hours ago";
        }
        else if (timeAgo.TotalMinutes > 1)
        {
            return $"{timeAgo.Minutes} minutes ago";
        }
        else
        {
            return "Now";
        }        
    }

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

    private async void UploadBackup()
    {
        uploading = true;
        uploadPercent = 0;
        var backup = Backup.ToBackup();
        await Orchestrator.BackupManager.UploadLocalBackupToOneDrive(backup, updateHassEntityState: false, progressCallback: (prog, speed) =>
        {
            uploadPercent = prog ?? 0;
            transferSpeed = speed ?? 0;
            TriggerStateChanged();

        });
        uploading = false;
        transferSpeed = 0;
        await Orchestrator.BackupManager.GetOnlineBackupsAsync(AddonOptions.InstanceName);
    }


    private async void DownloadBackup()
    {
        downloading = true;
        downloadPercent = 0;
        var onedriveBackup = Backup.ToOneDriveBackup();
        await Orchestrator.BackupManager.DownloadBackupFromOneDrive(onedriveBackup, updateHassEntityState: false, progressCallback: (prog) =>
        {
            downloadPercent = prog ?? 0;
            TriggerStateChanged();
        });

        downloading = false;
        await Orchestrator.BackupManager.GetLocalBackups();
    }

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

    }
}
