@namespace Oqtane.Modules.Admin.Sites
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject ISiteService SiteService
@inject ITenantService TenantService
@inject IAliasService AliasService
@inject IThemeService  ThemeService
@inject IStringLocalizer<Edit> Localizer

@if (_initialized)
{
    <table class="table table-borderless">
        <tr>
            <td>
                <Label For="name" HelpText="Enter the name of the site" ResourceKey="Name">Name: </Label>
            </td>
            <td>
                <input id="name" class="form-control" @bind="@_name" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="alias" HelpText="Enter the alias for the server" ResourceKey="Aliases">Aliases: </Label>
            </td>
            <td>
                <textarea id="alias" class="form-control" @bind="@_urls" rows="3" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="defaultTheme" HelpText="Select the default theme for the website" ResourceKey="DefaultTheme">Default Theme: </Label>
            </td>
            <td>
                <select id="defaultTheme" class="form-control" value="@_themetype" @onchange="(e => ThemeChanged(e))">
                    <option value="-">&lt;@Localizer["Select Theme"]&gt;</option>
                    @foreach (var theme in _themes)
                    {
                        <option value="@theme.TypeName">@theme.Name</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="defaultContainer" HelpText="Select the default container for the site" ResourceKey="DefaultContainer">Default Container: </Label>
            </td>
            <td>
                <select id="defaultIdea" class="form-control" @bind="@_containertype">
                    <option value="-">&lt;@Localizer["Select Container"]&gt;</option>
                    @foreach (var container in _containers)
                    {
                        <option value="@container.TypeName">@container.Name</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="defaultAdminContainer" HelpText="Select the default admin container for the site" ResourceKey="DefaultAdminContainer">Default Admin Container: </Label>
            </td>
            <td>
                <select id="defaultAdminContainer" class="form-control" @bind="@_admincontainertype">
                    <option value="-">&lt;@Localizer["Select Container"]&gt;</option>
                    <option value="">&lt;@Localizer["Default Admin Container"]&gt;</option>
                    @foreach (var container in _containers)
                    {
                        <option value="@container.TypeName">@container.Name</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="isDeleted" HelpText="Has this site been deleted?" ResourceKey="IsDeleted">Is Deleted? </Label>
            </td>
            <td>
                <select id="isDeleted" class="form-control" @bind="@_isdeleted">
                    <option value="True">@Localizer["Yes"]</option>
                    <option value="False">@Localizer["No"]</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="tenant" HelpText="The tenant for the site" ResourceKey="Tenant">Tenant: </Label>
            </td>
            <td>
                <input id="tenant" class="form-control" @bind="@_tenant" readonly />
            </td>
        </tr>

        <tr>
            <td>
                <Label For="connectionstring" HelpText="The database connection string" ResourceKey="ConnectionString">Connection String: </Label>
            </td>
            <td>
                <textarea id="connectionstring" class="form-control" @bind="@_connectionstring" rows="3" readonly></textarea>
            </td>
        </tr>
    </table>
    <br />
    <button type="button" class="btn btn-success" @onclick="SaveSite">@Localizer["Save"]</button>
    <NavLink class="btn btn-secondary" href="@NavigateUrl()">@Localizer["Cancel"]</NavLink>
    <br />
    <br />
    <AuditInfo CreatedBy="@_createdby" CreatedOn="@_createdon" ModifiedBy="@_modifiedby" ModifiedOn="@_modifiedon" DeletedBy="@_deletedby" DeletedOn="@_deletedon"></AuditInfo>
}

@code {
    private bool _initialized = false;
    private List<Theme> _themeList;
    private List<ThemeControl> _themes = new List<ThemeControl>();
    private List<ThemeControl> _containers = new List<ThemeControl>();
    private Alias _alias;
    private string _name = string.Empty;
    private List<Alias> _aliasList;
    private string _urls = string.Empty;
    private string _themetype;
    private string _containertype = "-";
    private string _admincontainertype = "-";
    private string _createdby;
    private DateTime _createdon;
    private string _modifiedby;
    private DateTime _modifiedon;
    private string _deletedby;
    private DateTime? _deletedon;
    private string _isdeleted;
    private string _tenant = string.Empty;
    private string _connectionstring = string.Empty;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _themeList = await ThemeService.GetThemesAsync();
            _aliasList = await AliasService.GetAliasesAsync();

            _alias = _aliasList.Find(item => item.AliasId == Int32.Parse(PageState.QueryString["id"]));
            SiteService.SetAlias(_alias);
            var site = await SiteService.GetSiteAsync(_alias.SiteId);
            if (site != null)
            {
                _name = site.Name;

                foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                {
                    _urls += alias.Name + "\n";
                }

                _themes = ThemeService.GetThemeControls(_themeList);
                _themetype = site.DefaultThemeType;
                _containers = ThemeService.GetContainerControls(_themeList, _themetype);
                _containertype = site.DefaultContainerType;
                _admincontainertype = site.AdminContainerType;
                _createdby = site.CreatedBy;
                _createdon = site.CreatedOn;
                _modifiedby = site.ModifiedBy;
                _modifiedon = site.ModifiedOn;
                _deletedby = site.DeletedBy;
                _deletedon = site.DeletedOn;
                _isdeleted = site.IsDeleted.ToString();

                List<Tenant> tenants = await TenantService.GetTenantsAsync();
                Tenant tenant = tenants.Find(item => item.TenantId == site.TenantId);
                if (tenant != null)
                {
                    _tenant = tenant.Name;
                    _connectionstring = tenant.DBConnectionString;
                }

                _initialized = true;
            }
        }
        catch (Exception ex)
        {
            await Log(_alias, LogLevel.Error, string.Empty, ex, "Error Loading Site {SiteId} {Error}", _alias.SiteId, ex.Message);
            AddModuleMessage(ex.Message, MessageType.Error);
        }
    }

    private async void ThemeChanged(ChangeEventArgs e)
    {
        try
        {
            _themetype = (string)e.Value;
            if (_themetype != "-")
            {
                _containers = ThemeService.GetContainerControls(_themeList, _themetype);
            }
            else
            {
                _containers = new List<ThemeControl>();
            }
            _containertype = "-";
            _admincontainertype = "";
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", _themetype, ex.Message);
            AddModuleMessage(Localizer["Error Loading Pane Layouts For Theme"], MessageType.Error);
        }
    }

    private async Task SaveSite()
    {
        try
        {
            if (_name != string.Empty && _urls != string.Empty && _themetype != "-" && _containertype != "-")
            {
                var unique = true;
                foreach (string name in _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (_aliasList.Exists(item => item.Name == name && item.SiteId != _alias.SiteId && item.TenantId != _alias.TenantId))
                    {
                        unique = false;
                    }
                }

                if (unique)
                {
                    SiteService.SetAlias(_alias);
                    var site = await SiteService.GetSiteAsync(_alias.SiteId);
                    if (site != null)
                    {
                        site.Name = _name;
                        site.LogoFileId = null;
                        site.DefaultThemeType = _themetype;
                        site.DefaultContainerType = _containertype;
                        site.AdminContainerType = _admincontainertype;
                        site.IsDeleted = (_isdeleted == null || Boolean.Parse(_isdeleted));

                        site = await SiteService.UpdateSiteAsync(site);

                        _urls = _urls.Replace("\n", ",");
                        var names = _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                        {
                            if (!names.Contains(alias.Name))
                            {
                                await AliasService.DeleteAliasAsync(alias.AliasId);
                            }
                        }

                        foreach (string name in names)
                        {
                            if (!_aliasList.Exists(item => item.Name == name))
                            {
                                Alias alias = new Alias
                                {
                                    Name = name,
                                    TenantId = site.TenantId,
                                    SiteId = site.SiteId
                                };
                                await AliasService.AddAliasAsync(alias);
                            }
                        }

                        await Log(_alias, LogLevel.Information, PermissionNames.Edit, null, "Site Saved {Site}", site);

                        NavigationManager.NavigateTo(NavigateUrl());
                    }
                }
                else
                {
                    AddModuleMessage(Localizer["An Alias Specified Has Already Been Used For Another Site"], MessageType.Warning);
                }
            }
            else
            {
                AddModuleMessage(Localizer["You Must Provide A Site Name, Alias, And Default Theme/Container"], MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await Log(_alias, LogLevel.Error, string.Empty, ex, "Error Saving Site {SiteId} {Error}", _alias.SiteId, ex.Message);
            AddModuleMessage(Localizer["Error Saving Site"], MessageType.Error);
        }
    }
}
