@page "/admin/system/mail"

@using Moonlight.Shared.Components.Navigations
@using Moonlight.Shared.Components.FileManagerPartials
@using Moonlight.App.Helpers.Files
@using Moonlight.App.Helpers
@using BlazorTable
@using Moonlight.App.Models.Misc
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Moonlight.App.Services.Mail
@using Moonlight.App.Services.Sessions

@inject SmartTranslateService SmartTranslateService
@inject ToastService ToastService
@inject AlertService AlertService
@inject MailService MailService
@inject IdentityService IdentityService

@attribute [PermissionRequired(nameof(Permissions.AdminSysMail))]

<AdminSystemNavigation Index="9"/>

<div class="card mb-3">
    <div class="card-header">
        <span class="card-title">
            <TL>Actions</TL>
        </span>
    </div>
    <div class="card-body">
        <WButton Text="@(SmartTranslateService.Translate("Test mail configuration"))"
                 WorkingText="@(SmartTranslateService.Translate("Sending test mail"))"
                 CssClasses="btn-primary"
                 OnClick="SendTestMail">
        </WButton>
    </div>
</div>

<LazyLoader @ref="LazyLoader" Load="Load">
    @if (CurrentMailTemplate == null)
    {
        <div class="card">
            <div class="card-header">
                <span class="card-title">
                    <TL>Mail templates</TL>
                </span>
                <div class="card-toolbar">
                    <WButton Text="@(SmartTranslateService.Translate("New mail template"))"
                             CssClasses="btn-sm btn-success"
                             OnClick="CreateNewMailTemplate">
                    </WButton>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <Table TableItem="MailTemplate" Items="MailTemplateFiles" PageSize="25" TableClass="table table-row-bordered table-row-gray-100 align-middle gs-0 gy-3" TableHeadClass="fw-bold text-muted">
                        <Column TableItem="MailTemplate" Title="@(SmartTranslateService.Translate("Name"))" Field="@(x => x.Name)" Sortable="true" Filterable="true">
                            <Template>
                                @{
                                    var name = context.Name.Replace(Path.GetExtension(context.Name), "");
                                }

                                <span>@(name)</span>
                            </Template>
                        </Column>
                        <Column TableItem="MailTemplate" Title="" Field="@(x => x.Name)" Filterable="false" Sortable="false">
                            <Template>
                                <div class="text-end">
                                    <WButton Text="@(SmartTranslateService.Translate("Edit"))"
                                             OnClick="() => EditTemplate(context)">
                                    </WButton>
                                    <DeleteButton OnClick="() => DeleteTemplate(context)"
                                                  Confirm="true">
                                    </DeleteButton>
                                </div>
                            </Template>
                        </Column>
                        <Pager ShowPageNumber="true" ShowTotalCount="true"/>
                    </Table>
                </div>
            </div>
        </div>
    }
    else
    {
        <FileEditor Language="html"
                    HideControls="false"
                    InitialData="@(CurrentMailTemplateContent)"
                    OnCancel="OnCancelTemplateEdit"
                    OnSubmit="OnSubmitTemplateEdit"/>
    }
</LazyLoader>

@code
{
    

    private MailTemplate[] MailTemplateFiles;
    private FileAccess FileAccess;
    private LazyLoader LazyLoader;

    #region Template Editor

    private MailTemplate? CurrentMailTemplate;
    private string CurrentMailTemplateContent = "";

    private async Task Load(LazyLoader arg)
    {
        FileAccess = new HostFileAccess(PathBuilder.Dir("storage"));

        await FileAccess.Cd("resources");
        await FileAccess.Cd("mail");

        MailTemplateFiles = (await FileAccess.Ls())
            .Where(x => x.IsFile)
            .Select(x => new MailTemplate()
            {
                Name = x.Name,
                File = x
            })
            .ToArray();
    }

    private async Task EditTemplate(MailTemplate mailTemplate)
    {
        CurrentMailTemplate = mailTemplate;

        CurrentMailTemplateContent = await FileAccess
            .Read(CurrentMailTemplate.File);

        await InvokeAsync(StateHasChanged);
    }

    private async Task DeleteTemplate(MailTemplate mailTemplate)
    {
        await FileAccess.Delete(mailTemplate.File);
        await LazyLoader.Reload();
    }

    private async void OnCancelTemplateEdit()
    {
        CurrentMailTemplate = null;
        await InvokeAsync(StateHasChanged);
    }

    private async void OnSubmitTemplateEdit(string text)
    {
        await FileAccess.Write(CurrentMailTemplate!.File, text);

        await ToastService.Success(
            SmartTranslateService.Translate("Successfully saved file"));
    }

    private async Task CreateNewMailTemplate()
    {
        var name = await AlertService.Text(
            SmartTranslateService.Translate("New mail template"),
            SmartTranslateService.Translate("Enter the name of the new template"),
            ""
            );

        if (string.IsNullOrEmpty(name))
            return;

        await FileAccess.Write(new()
        {
            Name = name + ".html"
        }, "");

        await LazyLoader.Reload();
    }

    #endregion

    private async Task SendTestMail()
    {
        await MailService.SendMailRaw(IdentityService.User, "<html><body>If you see this mail, your moonlight mail configuration is ready to use</body></html>");
        await AlertService.Info(SmartTranslateService.Translate("A test mail has been sent to the email address of your account"));
    }
}