@namespace Oqtane.Modules.Admin.Site
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject ISiteService SiteService
@inject ITenantService TenantService
@inject IAliasService AliasService
@inject IThemeService  ThemeService
@inject ISettingService  SettingService
@inject IStringLocalizer<Index> Localizer
@inject INotificationService NotificationService

@if (_initialized)
{
    <table class="table table-borderless">
        <tr>
            <td>
                <Label For="name" HelpText="Enter the site name" ResourceKey="Name">Name: </Label>
            </td>
            <td>
                <input id="name" class="form-control" @bind="@_name" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="tenant" HelpText="Enter 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="alias" HelpText="Enter the alias for the server" ResourceKey="Aliases">Aliases: </Label>
            </td>
            <td>
                <textarea id="alias" class="form-control" @bind="@_urls" rows="3"></textarea>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="allowRegister" HelpText="Do you want the users to be able to register for an account on the site" ResourceKey="AllowRegistration">Allow User Registration? </Label>
            </td>
            <td>
                <select id="allowRegister" class="form-control" @bind="@_allowregistration">
                    <option value="True">@Localizer["Yes"]</option>
                    <option value="False">@Localizer["No"]</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="isDeleted" HelpText="Is this site 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>
    </table>
    <Section Name="Appearance" Heading="Appearance" ResourceKey="Appearance">
    <table class="table table-borderless">
        <tr>
            <td>
                <Label For="logo" HelpText="Specify a logo for the site" ResourceKey="Logo">Logo: </Label>
            </td>
            <td>
                <FileManager FileId="@_logofileid" Filter="@Constants.ImageFiles" @ref="_logofilemanager" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="favicon" HelpText="Specify a Favicon" ResourceKey="FavoriteIcon">Favicon: </Label>
            </td>
            <td>
                <FileManager FileId="@_faviconfileid" Filter="ico" @ref="_faviconfilemanager" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="defaultTheme" HelpText="Select the sites default theme" 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="defaultContainer" 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>
    </table>
    </Section>
    <Section Name="SMTP" Heading="SMTP Settings" ResourceKey="SMTPSettings">
        <table class="table table-borderless">
            <tr>
                <td colspan="2">
                    <strong>@Localizer["Please Note That SMTP Requires The Notification Job To Be Enabled In Scheduled Jobs"]</strong>
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="host" HelpText="Enter the host name of the SMTP server" ResourceKey="Host">Host: </Label>
                </td>
                <td>
                    <input id="host" class="form-control" @bind="@_smtphost" />
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="port" HelpText="Enter the port number for the SMTP server. Please note this field is required if you provide a host name." ResourceKey="Port">Port: </Label>
                </td>
                <td>
                    <input id="port" class="form-control" @bind="@_smtpport" />
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="enabledSSl" HelpText="Specify if SSL is required for your SMTP server" ResourceKey="UseSsl">SSL Enabled: </Label>
                </td>
                <td>
                    <select id="enabledSSl" class="form-control" @bind="@_smtpssl">
                        <option value="True">@Localizer["Yes"]</option>
                        <option value="False">@Localizer["No"]</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="username" HelpText="Enter the username for your SMTP account" ResourceKey="SmptUsername">Username: </Label>
                </td>
                <td>
                    <input id="username" class="form-control" @bind="@_smtpusername" />
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="password" HelpText="Enter the password for your SMTP account" ResourceKey="SmtpPassword">Password: </Label>
                </td>
                <td>
                    <input id="password" type="password" class="form-control" @bind="@_smtppassword" />
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="sender" HelpText="Enter the email which emails will be sent from. Please note that this email address may need to be authorized with the SMTP server." ResourceKey="SmptSender">Email Sender: </Label>
                </td>
                <td>
                    <input id="sender" class="form-control" @bind="@_smtpsender" />
                </td>
            </tr>
        </table>
        <button type="button" class="btn btn-secondary" @onclick="SendEmail">@Localizer["Test SMTP Configuration"]</button>
        <br /><br />
    </Section>
    <Section Name="PWA" Heading="Progressive Web Application Settings" ResourceKey="PWASettings">
        <table class="table table-borderless">
            <tr>
                <td>
                    <Label For="isEnabled" HelpText="Select whether you would like this site to be available as a Progressive Web Application (PWA)" ResourceKey="EnablePWA">Is Enabled? </Label>
                </td>
                <td>
                    <select id="isEnabled" class="form-control" @bind="@_pwaisenabled">
                        <option value="True">@Localizer["Yes"]</option>
                        <option value="False">@Localizer["No"]</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="appIcon" HelpText="Include an application icon for your PWA. It should be a PNG which is 192 X 192 pixels in dimension." ResourceKey="PwaApplicationIcon">App Icon: </Label>
                </td>
                <td>
                    <FileManager FileId="@_pwaappiconfileid" Filter="png" @ref="_pwaappiconfilemanager" />
                </td>
            </tr>
            <tr>
                <td>
                    <Label For="splashIcon" HelpText="Include a splash icon for your PWA. It should be a PNG which is 512 X 512 pixels in dimension." ResourceKey="PwaSplashIcon">Splash Icon: </Label>
                </td>
                <td>
                    <FileManager FileId="@_pwasplashiconfileid" Filter="png" @ref="_pwasplashiconfilemanager" />
                </td>
            </tr>
        </table>
    </Section>

    <br />
    <button type="button" class="btn btn-success" @onclick="SaveSite">@Localizer["Save"]</button>
    <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 string _name = string.Empty;
    private List<Tenant> _tenantList;
    private string _tenant = string.Empty;
    private List<Alias> _aliasList;
    private string _urls = string.Empty;
    private int _logofileid = -1;
    private FileManager _logofilemanager;
    private int _faviconfileid = -1;
    private FileManager _faviconfilemanager;
    private string _themetype = "-";
    private string _containertype = "-";
    private string _admincontainertype = "-";
    private string _allowregistration;
    private string _smtphost = string.Empty;
    private string _smtpport = string.Empty;
    private string _smtpssl = "False";
    private string _smtpusername = string.Empty;
    private string _smtppassword = string.Empty;
    private string _smtpsender = string.Empty;
    private string _pwaisenabled;
    private int _pwaappiconfileid = -1;
    private FileManager _pwaappiconfilemanager;
    private int _pwasplashiconfileid = -1;
    private FileManager _pwasplashiconfilemanager;
    private string _createdby;
    private DateTime _createdon;
    private string _modifiedby;
    private DateTime _modifiedon;
    private string _deletedby;
    private DateTime? _deletedon;
    private string _isdeleted;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _themeList = await ThemeService.GetThemesAsync();
            _aliasList = await AliasService.GetAliasesAsync();
            Site site = await SiteService.GetSiteAsync(PageState.Site.SiteId);
            if (site != null)
            {
                _name = site.Name;
                _tenantList = await TenantService.GetTenantsAsync();
                _tenant = _tenantList.Find(item => item.TenantId == site.TenantId).Name;
                foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                {
                    _urls += alias.Name + "\n";
                }
                if (site.LogoFileId != null)
                {
                    _logofileid = site.LogoFileId.Value;
                }

                if (site.FaviconFileId != null)
                {
                    _faviconfileid = site.FaviconFileId.Value;
                }

                _themes = ThemeService.GetThemeControls(_themeList);
                _themetype = site.DefaultThemeType;
                _containers = ThemeService.GetContainerControls(_themeList, _themetype);
                _containertype = site.DefaultContainerType;
                _admincontainertype = site.AdminContainerType;
                _allowregistration = site.AllowRegistration.ToString();

                var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);
                _smtphost = SettingService.GetSetting(settings, "SMTPHost", string.Empty);
                _smtpport = SettingService.GetSetting(settings, "SMTPPort", string.Empty);
                _smtpssl = SettingService.GetSetting(settings, "SMTPSSL", "False");
                _smtpusername = SettingService.GetSetting(settings, "SMTPUsername", string.Empty);
                _smtppassword = SettingService.GetSetting(settings, "SMTPPassword", string.Empty);
                _smtpsender = SettingService.GetSetting(settings, "SMTPSender", string.Empty);

                _pwaisenabled = site.PwaIsEnabled.ToString();

                if (site.PwaAppIconFileId != null)
                {
                    _pwaappiconfileid = site.PwaAppIconFileId.Value;
                }

                if (site.PwaSplashIconFileId != null)
                {
                    _pwasplashiconfileid = site.PwaSplashIconFileId.Value;
                }

                _pwaisenabled = site.PwaIsEnabled.ToString();
                if (site.PwaAppIconFileId != null)
                {
                    _pwaappiconfileid = site.PwaAppIconFileId.Value;
                }
                if (site.PwaSplashIconFileId != null)
                {
                    _pwasplashiconfileid = site.PwaSplashIconFileId.Value;
                }

                _createdby = site.CreatedBy;
                _createdon = site.CreatedOn;
                _modifiedby = site.ModifiedBy;
                _modifiedon = site.ModifiedOn;
                _deletedby = site.DeletedBy;
                _deletedon = site.DeletedOn;
                _isdeleted = site.IsDeleted.ToString();

                _initialized = true;
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Site {SiteId} {Error}", PageState.Site.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 != PageState.Alias.SiteId && item.TenantId != PageState.Alias.TenantId))
                    {
                        unique = false;
                    }
                }

                if (unique)
                {
                    var site = await SiteService.GetSiteAsync(PageState.Site.SiteId);
                    if (site != null)
                    {
                        site.Name = _name;
                        site.LogoFileId = null;
                        var logofileid = _logofilemanager.GetFileId();
                        if (logofileid != -1)
                        {
                            site.LogoFileId = logofileid;
                        }


                        var faviconFieldId = _faviconfilemanager.GetFileId();
                        if (faviconFieldId != -1)
                        {
                            site.FaviconFileId = faviconFieldId;
                        }

                        site.DefaultThemeType = _themetype;
                        site.DefaultContainerType = _containertype;
                        site.AdminContainerType = _admincontainertype;
                        site.AllowRegistration = (_allowregistration == null ? true : Boolean.Parse(_allowregistration));
                        site.IsDeleted = (_isdeleted == null ? true : Boolean.Parse(_isdeleted));

                        site.PwaIsEnabled = (_pwaisenabled == null ? true : Boolean.Parse(_pwaisenabled));

                        var pwaappiconfileid = _pwaappiconfilemanager.GetFileId();
                        if (pwaappiconfileid != -1)
                        {
                            site.PwaAppIconFileId = pwaappiconfileid;
                        }

                        var pwasplashiconfileid = _pwasplashiconfilemanager.GetFileId();
                        if (pwasplashiconfileid != -1)
                        {
                            site.PwaSplashIconFileId = pwasplashiconfileid;
                        }

                        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();
                                alias.Name = name;
                                alias.TenantId = site.TenantId;
                                alias.SiteId = site.SiteId;
                                await AliasService.AddAliasAsync(alias);
                            }
                        }

                        var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);
                        SettingService.SetSetting(settings, "SMTPHost", _smtphost);
                        SettingService.SetSetting(settings, "SMTPPort", _smtpport);
                        SettingService.SetSetting(settings, "SMTPSSL", _smtpssl);
                        SettingService.SetSetting(settings, "SMTPUsername", _smtpusername);
                        SettingService.SetSetting(settings, "SMTPPassword", _smtppassword);
                        SettingService.SetSetting(settings, "SMTPSender", _smtpsender);
                        await SettingService.UpdateSiteSettingsAsync(settings, site.SiteId);

                        await logger.LogInformation("Site Settings Saved {Site}", site);
                        AddModuleMessage(Localizer["Site Settings Saved"], MessageType.Success);
                    }
                }
                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 logger.LogError(ex, "Error Saving Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);
            AddModuleMessage(Localizer["Error Saving Site"], MessageType.Error);
        }
    }

    private async Task SendEmail()
    {
        if (_smtphost != "" && _smtpport != "" && _smtpsender != "")
        {
            try
            {
                var settings = await SettingService.GetSiteSettingsAsync(PageState.Site.SiteId);
                SettingService.SetSetting(settings, "SMTPHost", _smtphost);
                SettingService.SetSetting(settings, "SMTPPort", _smtpport);
                SettingService.SetSetting(settings, "SMTPSSL", _smtpssl);
                SettingService.SetSetting(settings, "SMTPUsername", _smtpusername);
                SettingService.SetSetting(settings, "SMTPPassword", _smtppassword);
                SettingService.SetSetting(settings, "SMTPSender", _smtpsender);
                await SettingService.UpdateSiteSettingsAsync(settings, PageState.Site.SiteId);
                await logger.LogInformation("Site SMTP Settings Saved");

                await NotificationService.AddNotificationAsync(new Notification(PageState.Site.SiteId, PageState.User.DisplayName, PageState.User.Email, PageState.User.DisplayName, PageState.User.Email, PageState.Site.Name + " SMTP Configuration Test", "SMTP Server Is Configured Correctly."));
                AddModuleMessage(Localizer["SMTP Settings Saved And A Message Has Been Sent To The Email Address Associated To Your User Account... Please Wait A Few Minutes For Delivery. If You Do Not Receive The Email Please Review The Notification Job In Scheduled Jobs For Any Log Details."], MessageType.Info);
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Testing SMTP Configuration");
                AddModuleMessage(Localizer["Error Testing SMTP Configuration"], MessageType.Error);
            }
        }
        else
        {
            AddModuleMessage(Localizer["You Must Specify The SMTP Host, Port, And Sender"], MessageType.Warning);
        }

    }
}
