@namespace Oqtane.Modules.Admin.Modules
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IThemeService ThemeService
@inject IModuleService ModuleService
@inject IPageModuleService PageModuleService

<TabStrip>
    <TabPanel Name="Settings" Heading="Module Settings">
        @if (_containers != null)
        {
            <table class="table table-borderless">
                <tr>
                    <td>
                        <Label For="title" HelpText="Enter the title of the module">Title: </Label>
                    </td>
                    <td>
                        <input id="title" type="text" name="Title" class="form-control" @bind="@_title" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <Label For="container" HelpText="Select the module's container">Container: </Label>
                    </td>
                    <td>
                        <select id="container" class="form-control" @bind="@_containerType">
                            <option value="-">&lt;Inherit From Page Or Site&gt;</option>
                            @foreach (var container in _containers)
                            {
                                <option value="@container.TypeName">@container.Name</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>
                        <Label For="allpages" HelpText="Indicate if this module should be displayed on all pages">Display On All Pages? </Label>
                    </td>
                    <td>
                        <select id="allpages" class="form-control" @bind="@_allPages">
                            <option value="True">Yes</option>
                            <option value="False">No</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>
                        <Label For="page" HelpText="The page that the module is on">Page: </Label>
                    </td>
                    <td>
                        <select id="page" class="form-control" @bind="@_pageId">
                            @foreach (Page p in PageState.Pages)
                            {
                                if (UserSecurity.IsAuthorized(PageState.User, PermissionNames.View, p.Permissions))
                                {
                                    <option value="@p.PageId">@(new string('-', p.Level * 2))@(p.Name)</option>
                                }
                            }
                        </select>
                    </td>
                </tr>
            </table>
        }
    </TabPanel>
    <TabPanel Name="Permissions">
        @if (_permissions != null)
        {
            <table class="table table-borderless">
                <tr>
                    <td>
                        <PermissionGrid EntityName="@EntityNames.Module" PermissionNames="@_permissionNames" Permissions="@_permissions" @ref="_permissionGrid" />
                    </td>
                </tr>
            </table>
        }
    </TabPanel>
    @if (_settingsModuleType != null)
    {
        <TabPanel Name="ModuleSettings" Heading="@_settingstitle">
            @DynamicComponent
        </TabPanel>
    }
</TabStrip>
<button type="button" class="btn btn-success" @onclick="SaveModule">Save</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">Cancel</NavLink>

@code {
    private List<ThemeControl> _containers = new List<ThemeControl>();
    private string _title;
    private string _containerType;
    private string _allPages = "false";
    private string _permissionNames = "";
    private string _permissions = null;
    private string _pageId;
    private PermissionGrid _permissionGrid;
    private Type _settingsModuleType;
    private string _settingstitle = "Other Settings";
    private object _settings;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Edit;
    public override string Title => "Module Settings";

    private RenderFragment DynamicComponent { get; set; }

    protected override async Task OnInitializedAsync()
    {
        _title = ModuleState.Title;
        _containers = ThemeService.GetContainerControls(await ThemeService.GetThemesAsync(), PageState.Page.ThemeType);
        _containerType = ModuleState.ContainerType;
        if (!string.IsNullOrEmpty(PageState.Page.DefaultContainerType) && _containerType == PageState.Page.DefaultContainerType)
        {
            _containerType = "-";
        }
        if (_containerType == PageState.Site.DefaultContainerType)
        {
            _containerType = "-";
        }
        _allPages = ModuleState.AllPages.ToString();
        _permissions = ModuleState.Permissions;
        _permissionNames = ModuleState.ModuleDefinition.PermissionNames;
        _pageId = ModuleState.PageId.ToString();

        _settingsModuleType = Type.GetType(ModuleState.ModuleType);
        if (_settingsModuleType != null)
        {
            var moduleobject = Activator.CreateInstance(_settingsModuleType) as IModuleControl;
            _settingstitle = moduleobject.Title;
            if (string.IsNullOrEmpty(_settingstitle))
            {
                _settingstitle = "Other Settings";
            }

            DynamicComponent = builder =>
            {
                builder.OpenComponent(0, _settingsModuleType);
                builder.AddComponentReferenceCapture(1, inst => { _settings = Convert.ChangeType(inst, _settingsModuleType); });
                builder.CloseComponent();
            };
        }
    }

    private async Task SaveModule()
    {
        var pagemodule = await PageModuleService.GetPageModuleAsync(ModuleState.PageModuleId);
        pagemodule.PageId = int.Parse(_pageId);
        pagemodule.Title = _title;
        pagemodule.ContainerType = (_containerType != "-") ? _containerType : string.Empty;
        if (!string.IsNullOrEmpty(pagemodule.ContainerType) && pagemodule.ContainerType == PageState.Page.DefaultContainerType)
        {
            pagemodule.ContainerType = string.Empty;
        }
        if (!string.IsNullOrEmpty(pagemodule.ContainerType) && pagemodule.ContainerType == PageState.Site.DefaultContainerType)
        {
            pagemodule.ContainerType = string.Empty;
        }
        await PageModuleService.UpdatePageModuleAsync(pagemodule);
        await PageModuleService.UpdatePageModuleOrderAsync(pagemodule.PageId, pagemodule.Pane);

        var module = ModuleState;
        module.AllPages = bool.Parse(_allPages);
        module.Permissions = _permissionGrid.GetPermissions();
        await ModuleService.UpdateModuleAsync(module);

        if (_settingsModuleType != null)
        {
            var moduleType = Type.GetType(ModuleState.ModuleType);
            if (moduleType != null)
            {
                moduleType.GetMethod("UpdateSettings")?.Invoke(_settings, null); // method must be public in settings component
            }
        }

        NavigationManager.NavigateTo(NavigateUrl());
    }

}
