@namespace Oqtane.Modules.Admin.Files
@inherits ModuleBase
@inject IFolderService FolderService
@inject NavigationManager NavigationManager

@if (_folders != null)
{
    <table class="table table-borderless">
        <tr>
            <td>
                <Label For="parent" HelpText="Select the parent folder">Parent: </Label>
            </td>
            <td>
                <select id="parent" class="form-control" @bind="@_parentId">
                    @if (PageState.QueryString.ContainsKey("id"))
                    {
                        <option value="-1">&lt;No Parent&gt;</option>
                    }
                    @foreach (Folder folder in _folders)
                    {
                        <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label for="name" HelpText="Enter the folder name">Name: </Label>
            </td>
            <td>
                <input id="name" class="form-control" @bind="@_name" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <Label For="permissions" HelpText="Select the permissions you want for the folder">Permissions: </Label>
                <PermissionGrid EntityName="@EntityNames.Folder" PermissionNames="Browse,View,Edit" Permissions="@_permissions" @ref="_permissionGrid" />
            </td>
        </tr>
    </table>
    @if (!_isSystem)
    {
        <button type="button" class="btn btn-success" @onclick="SaveFolder">Save</button>
    }
    <NavLink class="btn btn-secondary" href="@NavigateUrl()">Cancel</NavLink>
    @if (!_isSystem && PageState.QueryString.ContainsKey("id"))
    {
        <button type="button" class="btn btn-danger" @onclick="DeleteFolder">Delete</button>
    }
    <br />
    <br />
    @if (PageState.QueryString.ContainsKey("id"))
    {
        <AuditInfo CreatedBy="@_createdBy" CreatedOn="@_createdOn" ModifiedBy="@_modifiedBy" ModifiedOn="@_modifiedOn"></AuditInfo>
    }
}

@code {
    private List<Folder> _folders;
    private int _folderId = -1;
    private string _name;
    private int _parentId = -1;
    private bool _isSystem;
    private string _permissions = string.Empty;
    private string _createdBy;
    private DateTime _createdOn;
    private string _modifiedBy;
    private DateTime _modifiedOn;

#pragma warning disable 649
    private PermissionGrid _permissionGrid;
#pragma warning restore 649

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    public override string Title => "Folder Management";

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _folders = await FolderService.GetFoldersAsync(PageState.Site.SiteId);

            if (PageState.QueryString.ContainsKey("id"))
            {
                _folderId = Int32.Parse(PageState.QueryString["id"]);
                Folder folder = await FolderService.GetFolderAsync(_folderId);
                if (folder != null)
                {
                    _parentId = folder.ParentId ?? -1;
                    _name = folder.Name;
                    _isSystem = folder.IsSystem;
                    _permissions = folder.Permissions;
                    _createdBy = folder.CreatedBy;
                    _createdOn = folder.CreatedOn;
                    _modifiedBy = folder.ModifiedBy;
                    _modifiedOn = folder.ModifiedOn;
                }
            }
            else
            {
                _parentId = _folders[0].FolderId;
                _permissions = string.Empty;
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Folder {FolderId} {Error}", _folderId, ex.Message);
            AddModuleMessage("Error Loading Folder", MessageType.Error);
        }
    }

    private async Task SaveFolder()
    {
        if (_name == string.Empty || _parentId == -1)
        {
            AddModuleMessage("Folders Must Have A Parent And A Name", MessageType.Warning);
            return;
        }

        if (!_name.IsPathOrFileValid())
        {
            AddModuleMessage("Folder Name Not Valid.", MessageType.Warning);
            return;
        }
        
        try
        {
            Folder folder;
            if (_folderId != -1)
            {
                folder = await FolderService.GetFolderAsync(_folderId);
            }
            else
            {
                folder = new Folder();
            }

            folder.SiteId = PageState.Site.SiteId;

            if (_parentId == -1)
            {
                folder.ParentId = null;
            }
            else
            {
                folder.ParentId = _parentId;
            }

            folder.Name = _name;
            folder.IsSystem = _isSystem;
            folder.Permissions = _permissionGrid.GetPermissions();

            if (_folderId != -1)
            {
                folder = await FolderService.UpdateFolderAsync(folder);
            }
            else
            {
                folder = await FolderService.AddFolderAsync(folder);
            }

            if (folder != null)
            {
                await FolderService.UpdateFolderOrderAsync(folder.SiteId, folder.FolderId, folder.ParentId);
                await logger.LogInformation("Folder Saved {Folder}", folder);
                NavigationManager.NavigateTo(NavigateUrl());
            }
            else
            {
                AddModuleMessage("An Error Was Encountered Saving The Folder", MessageType.Error);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Saving Folder {FolderId} {Error}", _folderId, ex.Message);
            AddModuleMessage("Error Saving Module", MessageType.Error);
        }
    }

    private async Task DeleteFolder()
    {
        try
        {
            await FolderService.DeleteFolderAsync(_folderId);
            await logger.LogInformation("Folder Deleted {Folder}", _folderId);
            AddModuleMessage("Folder Deleted", MessageType.Success);
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting Folder {Folder} {Error}", _folderId, ex.Message);
            AddModuleMessage("Error Deleting Folder", MessageType.Error);
        }
    }
}
