@namespace Oqtane.Modules.Admin.Files
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IFolderService FolderService
@inject IFileService FileService
@inject IStringLocalizer<Index> Localizer

@if (_files != null)
{
    <table class="table table-borderless">
        <tr>
            <td>
                <label  class="control-label">@Localizer["Folder:"] </label>
            </td>
            <td>
                <select class="form-control" @onchange="(e => FolderChanged(e))">
                    @foreach (Folder folder in _folders)
                    {
                        <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
                    }
                </select>
            </td>
            <td>
                <ActionLink Action="Edit" Text="Edit Folder" Class="btn btn-secondary" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="EditFolder" />&nbsp;
                <ActionLink Action="Edit" Text="Add Folder" Class="btn btn-secondary" ResourceKey="AddFolder" />&nbsp;
                <ActionLink Action="Add" Text="Upload Files" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="UploadFiles" />
            </td>
        </tr>
    </table>
    <Pager Items="@_files">
        <Header>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th>@Localizer["Name"]</th>
            <th>@Localizer["Modified"]</th>
            <th>@Localizer["Type"]</th>
            <th>@Localizer["Size"]</th>
        </Header>
        <Row>
            <td><ActionLink Action="Details" Text="Edit" Parameters="@($"id=" + context.FileId.ToString())" ResourceKey="Details" /></td>
            <td><ActionDialog Header="Delete File" Message="@Localizer["Are You Sure You Wish To Delete {0}?", context.Name]" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteFile(context))" ResourceKey="DeleteFile" /></td>
            <td><a href="@(ContentUrl(context.FileId))" target="_new">@context.Name</a></td>
            <td>@context.ModifiedOn</td>
            <td>@context.Extension.ToUpper() @Localizer["File"]</td>
            <td>@string.Format("{0:0.00}", ((decimal)context.Size / 1000)) KB</td>
        </Row>
    </Pager>
    @if (_files.Count == 0)
    {
        <div class="text-center">@Localizer["No Files Exist In Selected Folder"]</div>
    }
}

@code {
    private List<Folder> _folders;
    private int _folderId = -1;
    private List<File> _files;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnParametersSetAsync()
    {
        try
        {
            _folders = await FolderService.GetFoldersAsync(PageState.Site.SiteId);
            
            if (_folderId == -1 && _folders.Count > 0)
            {
                _folderId = _folders[0].FolderId;
                await GetFiles();
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Files {Error}", ex.Message);
            AddModuleMessage(Localizer["Error Loading Files"], MessageType.Error);
        }
    }

    private async Task GetFiles()
    {
        _files = await FileService.GetFilesAsync(_folderId);
    }

    private async void FolderChanged(ChangeEventArgs e)
    {
        try
        {
            _folderId = int.Parse((string)e.Value);
            await GetFiles();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Files {Error}", ex.Message);
            AddModuleMessage(Localizer["Error Loading Files"], MessageType.Error);
        }
    }

    private async Task DeleteFile(File file)
    {
        try
        {
            await FileService.DeleteFileAsync(file.FileId);
            await logger.LogInformation("File Deleted {File}", file.Name);
            AddModuleMessage(Localizer["File {0} Deleted", file.Name], MessageType.Success);
            await GetFiles();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting File {File} {Error}", file.Name, ex.Message);
            AddModuleMessage(Localizer["Error Deleting File {0}", file.Name], MessageType.Error);
        }
    }
}
