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

@if (_files == null)
{
    <p>
        <em>@SharedLocalizer["Loading"]</em>
    </p>
}
else
{
    <TabStrip>
        <TabPanel Name="Files" Heading="Files" ResourceKey="Files">
            <div class="row">
                <div class="col-md mb-1">
                    <ActionLink Action="Edit" Text="Add Folder" Class="btn btn-secondary" ResourceKey="AddFolder" />
                </div>
                <div class="col-md-8 mb-1">
                    <div class="input-group">
                        <span class="input-group-text">@Localizer["Folder"]:</span>
                        <select class="form-select" @onchange="(e => FolderChanged(e))">
                            @foreach (Folder folder in _folders)
                            {
                                <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
                            }
                        </select>
                        <ActionLink Action="Edit" Text="Edit Folder" Class="btn btn-secondary" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="EditFolder" />&nbsp;
                    </div>
                </div>
                <div class="col-md mb-1 text-end">
                    <ActionLink Action="Add" Text="Upload Files" Parameters="@($"id=" + _folderId.ToString())" ResourceKey="UploadFiles" />
                </div>
            </div>

            @if (_files.Count != 0)
            {
                <Pager Items="@_files" SearchProperties="Name">
                    <Header>
                        <th style="width: 1px;">&nbsp;</th>
                        <th style="width: 1px;">&nbsp;</th>
                        <th>@SharedLocalizer["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="@string.Format(Localizer["Confirm.File.Delete"], context.Name)" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteFile(context))" ResourceKey="DeleteFile" /></td>
                        <td><a href="@context.Url" target="_new">@context.Name</a></td>
                        <td>@context.ModifiedOn</td>
                        <td>@context.Extension.ToUpper() @SharedLocalizer["File"]</td>
                        <td>@string.Format("{0:0.00}", ((decimal)context.Size / 1000)) KB</td>
                    </Row>
                </Pager>
            }
            else
            {
                <div class="text-center">@Localizer["NoFiles"]</div>
            }
        </TabPanel>
        <TabPanel Name="Settings" Heading="Settings" ResourceKey="Settings" Security="SecurityAccessLevel.Admin">
			<div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="imageExt" HelpText="Enter a comma separated list of image file extensions" ResourceKey="ImageExtensions">Image Extensions: </Label>
                    <div class="col-sm-9">
                        <input id="imageExt" spellcheck="false" class="form-control" @bind="@_imageFiles" />
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="uploadableFileExt" HelpText="Enter a comma separated list of uploadable file extensions" ResourceKey="UploadableFileExtensions">Uploadable File Extensions: </Label>
                    <div class="col-sm-9">
                        <input id="uploadableFileExt" spellcheck="false" class="form-control" @bind="@_uploadableFiles" />
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="maxChunkSize" HelpText="Files are split into chunks to streamline the upload process. Specify the maximum chunk size in MB (note that higher chunk sizes should only be used on faster networks)." ResourceKey="MaxChunkSize">Max Upload Chunk Size (MB): </Label>
                    <div class="col-sm-9">
                        <input id="maxChunkSize" type="number" min="1" max="10" step="1" class="form-control" @bind="@_maxChunkSize" />
                    </div>
                </div>
            </div>
            <br />
            <button type="button" class="btn btn-success" @onclick="SaveSiteSettings">@SharedLocalizer["Save"]</button>
        </TabPanel>
    </TabStrip>
}

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

    private string _imageFiles = string.Empty;
    private string _uploadableFiles = string.Empty;
    private int _maxChunkSize = 1;

    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();
            }

            var settings = await SettingService.GetSiteSettingsAsync(PageState.Site.SiteId);
            _imageFiles = SettingService.GetSetting(settings, "ImageFiles", Constants.ImageFiles);
            _imageFiles = (string.IsNullOrEmpty(_imageFiles)) ? Constants.ImageFiles : _imageFiles;
            _uploadableFiles = SettingService.GetSetting(settings, "UploadableFiles", Constants.UploadableFiles);
            _uploadableFiles = (string.IsNullOrEmpty(_uploadableFiles)) ? Constants.UploadableFiles : _uploadableFiles;
            _maxChunkSize = int.Parse(SettingService.GetSetting(settings, "MaxChunkSize", "1"));
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Files {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.File.Load"], 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.File.Load"], MessageType.Error);
        }
    }

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

    private async Task SaveSiteSettings()
    {
        try
        {
            var settings = await SettingService.GetSiteSettingsAsync(PageState.Site.SiteId);
            settings = SettingService.SetSetting(settings, "ImageFiles", (_imageFiles != Constants.ImageFiles) ? _imageFiles.Replace(" ", "") : "", false);
            settings = SettingService.SetSetting(settings, "UploadableFiles", (_uploadableFiles != Constants.UploadableFiles) ? _uploadableFiles.Replace(" ", "") : "", false);
            settings = SettingService.SetSetting(settings, "MaxChunkSize", _maxChunkSize.ToString(), false);
            await SettingService.UpdateSiteSettingsAsync(settings, PageState.Site.SiteId);
            AddModuleMessage(Localizer["Success.SaveSiteSettings"], MessageType.Success);
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Saving Site Settings {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.SaveSiteSettings"], MessageType.Error);
        }
    }

}
