@model Fakemail.Web.Models.UserModel

@using System.Linq;

@{
    ViewData["Title"] = "fakemail.stream";
}

<div class="text-left">
    <h5><em>A fake SMTP server for software integration testing.</em></h5>
</div>

<br />

<p><span style="font-weight: 700">Welcome, @Model.Username.</span></p>

<p>
Host: <span class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">@Model.SmtpServer.Host</span>
Port: <span class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">@Model.SmtpServer.Port</span>
Security: <span class="sourcecode">@Model.SmtpServer.AuthenticationType</span>
Username: <span class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">@Model.SmtpCredentials.First().SmtpUsername</span>
Password: <span class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">@Model.SmtpCredentials.First().SmtpPassword</span>
</p>

<button class="btn btn-secondary btn-sm" onclick="InjectTestEmail('@Model.UserId', '@Model.SmtpCredentials.First().SmtpUsername')">Create email (API)</button>
<button class="btn btn-secondary btn-sm" onclick="SendTestEmail('@Model.UserId', '@Model.SmtpCredentials.First().SmtpUsername')">Send email (SMTP)</button>
<button class="btn btn-secondary btn-sm" onclick="DeleteAllEmails('@Model.UserId', '@Model.SmtpCredentials.First().SmtpUsername')">Delete all</button>

<div id="_EmailSummaryTable">
    @await Html.PartialAsync("_EmailSummaryTable")
</div>

<div class="spinner-border" role="status"></div>
<br />
<span class="">Waiting for emails to arrive...</span>

<hr />

<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="bi bi-info-circle me-2"></i>
    Download emails using curl.exe:
<div class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">
<pre><span>curl.exe -X 'POST' \</span>
<span>'@Model.ApiExternalBaseUri/mail/list' \</span>
<span>-H 'Content-Type: application/json' \</span>
<span>-d '{\"userId\": \"@Model.UserId\",\"page\":1,\"pageSize\":10}'</span></pre>
    </div>
    <div class="sourcecode copyable-text" data-bs-toggle="tooltip" data-bs-placement="top" title="Copy to clipboard">
<pre><span>curl.exe -X 'POST' \</span>
<span>'@Model.ApiExternalBaseUri/mail/get' \</span>
<span>-H 'Content-Type: application/json' \</span>
<span>-d '{\"userId\": \"@Model.UserId\",\"emailId\":\"[email id as returned from /mail/list]\"}'</span></pre>
    </div>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

</div>

<iframe id="download_iframe" style="display:none;"></iframe>

@section Scripts {
<script type="text/javascript">

    window.onload = (event) => {
        setTimeout(() => UpdateTable(false), 10000);
        document.title = "Fakemail.stream";
    }

    function UpdateTable(isOneOff) {
        var nextUpdate = 10000;

        var sequenceNumber = Math.max(
            ...$('tr[sequenceNumber')
                .map((i, el) => parseInt($(el).attr('sequenceNumber'), 10))
                .get(), 
            -1
        );

        fetch("@Model.UserId/smtpuser/@Model.SmtpCredentials.First().SmtpUsername/update/" + sequenceNumber, {
            method: 'GET'
        })
        .then(response => {
          if (response.ok) {
            return response.text();
          } else {
            throw Error(response.statusText);
          }
        })
        .then(data => {
            if (data.length > 2) {
                $('#_EmailSummaryTableBody:first').prepend(data);
                nextUpdate = 5000;
            }
        })
        .catch(error => {
          console.log(error);
        });

        if (!isOneOff) {
            setTimeout(() => UpdateTable(false), nextUpdate);
        }
    }

    function InjectTestEmail(userId, smtpUsername) {
        var url = userId + '/smtpuser/' + smtpUsername + '/inject-test';
        fetch(url, {
            method: 'GET'
        })
        .then(response => UpdateTable(true));

        // TODO: error handling
    };

    function SendTestEmail(userId, smtpUsername) {
        var url = userId + '/smtpuser/' + smtpUsername + '/test-smtp';
        fetch(url, {
            method: 'GET'
        })
        .then(response => UpdateTable(true));

        // TODO: error handling
    };

    function DeleteAllEmails(userId, smtpUsername) {
        var url = userId + '/smtpuser/' + smtpUsername + '/email/*';
        fetch(url, {
            method: 'DELETE'
        })
        .then(response => {
            $('#_EmailSummaryTableBody').empty();
        });

        // TODO: error handling
    };
    
    function DownloadEmail(emailId) {
        var url = '@Model.UserId/email/' + emailId;
        document.getElementById('download_iframe').src = url;
    };

    function DeleteEmail(emailId) {
        $(".tr[emailId='" + emailId + "']").remove();

        var url = '@Model.UserId/email/' + emailId;
        fetch(url, {
            method: 'DELETE'
        })
        .then(response => response.text())
        .then(data => {
            // TODO: display notification
            $("tr[emailId='" + emailId + "']").remove();
        });
    }

</script>
}


