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

@if (_folders != null)
{
    <form @ref="form" class="@(validated ? "was-validated" : "needs-validation")" novalidate>
        <div class="container">
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="name" HelpText="The name of the file" ResourceKey="Name">Name: </Label>
                <div class="col-sm-9">
                    <input id="name" class="form-control" @bind="@_name" maxlength="50" required />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="parent" HelpText="The folder where the file is located" ResourceKey="Folder">Folder: </Label>
                <div class="col-sm-9">
                    <select id="parent" class="form-select" @bind="@_folderId" required>
                        @foreach (Folder folder in _folders)
                        {
                            <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
                        }
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="description" HelpText="A description of the file. This can be used as a caption for image files." ResourceKey="Description">Description: </Label>
                <div class="col-sm-9">
                    <input id="description" class="form-control" @bind="@_description" />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="size" HelpText="The size of the file (in bytes)" ResourceKey="Size">Size: </Label>
                <div class="col-sm-9">
                    <input id="size" class="form-control" @bind="@_size" readonly />
                </div>
            </div>
        </div>
        <br />
        <button type="button" class="btn btn-success" @onclick="SaveFile">@SharedLocalizer["Save"]</button>
        <NavLink class="btn btn-secondary" href="@NavigateUrl()">@SharedLocalizer["Cancel"]</NavLink>
        @if (_name.ToLower().EndsWith(".zip"))
        {
            <button type="button" class="btn btn-primary mx-1" @onclick="UnzipFile">Unzip</button>            
        }
        <br /><br />
        <AuditInfo CreatedBy="@_createdBy" CreatedOn="@_createdOn" ModifiedBy="@_modifiedBy" ModifiedOn="@_modifiedOn"></AuditInfo>
    </form>
}

@code {
    private ElementReference form;
    private bool validated = false;
    private int _fileId = -1;
    private string _name;
    private List<Folder> _folders;
    private int _folderId = -1;
    private string _description = string.Empty;
    private int _size;
    private string _createdBy;
    private DateTime _createdOn;
    private string _modifiedBy;
    private DateTime _modifiedOn;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    public override string Title => "File Management";

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _folders = await FolderService.GetFoldersAsync(PageState.Site.SiteId);
            _fileId = Int32.Parse(PageState.QueryString["id"]);
            File file = await FileService.GetFileAsync(_fileId);
            if (file != null)
            {
                _name = file.Name;
                _folderId = file.FolderId;
                _description = file.Description;
                _size = file.Size;
                _createdBy = file.CreatedBy;
                _createdOn = file.CreatedOn;
                _modifiedBy = file.ModifiedBy;
                _modifiedOn = file.ModifiedOn;
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading File {FileId} {Error}", _fileId, ex.Message);
            AddModuleMessage(Localizer["Error.File.Load"], MessageType.Error);
        }
    }

    private async Task SaveFile()
    {
        validated = true;
        var interop = new Interop(JSRuntime);
        if (await interop.FormValid(form))
        {
            try
            {
                if (_name.IsPathOrFileValid())
                {
                    File file = await FileService.GetFileAsync(_fileId);
                    file.Name = _name;
                    file.FolderId = _folderId;
                    file.Description = _description;
                    file = await FileService.UpdateFileAsync(file);
                    await logger.LogInformation("File Saved {File}", file);
                    NavigationManager.NavigateTo(NavigateUrl());
                }
                else
                {
                    AddModuleMessage(Localizer["Message.File.InvalidName"], MessageType.Warning);
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Saving File {FileId} {Error}", _fileId, ex.Message);
                AddModuleMessage(Localizer["Error.File.Save"], MessageType.Error);
            }
        }
        else
        {
            AddModuleMessage(SharedLocalizer["Message.InfoRequired"], MessageType.Warning);
        }
    }

    private async Task UnzipFile()
    {
        try
        {
            await FileService.UnzipFileAsync(_fileId);
            NavigationManager.NavigateTo(NavigateUrl());
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Unzipping File {FileId} {Error}", _fileId, ex.Message);
            AddModuleMessage(Localizer["Error.File.Unzip"], MessageType.Error);
        }
    }
}