@page
@model LoginModel

@{
    ViewData["Title"] = "Log in";
}

<div class="row" id="systemLogin">
    <div class="row">
        <h2><label class="col-md-2">Login Type</label></h2>
        <div class="btn-group col-md-4" role="group" aria-label="Login type">
            <input type="radio" class="btn-check" name="loginType" id="local-login" value="Local" v-model="loginType">
            <label class="btn btn-outline-primary" for="local-login">Local</label>

            <input type="radio" class="btn-check" name="loginType" id="ad-login" value="AD" v-model="loginType" checked>
            <label class="btn btn-outline-primary" for="ad-login">AD</label>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4" v-if="loginType == 'Local'">
            <form id="account" method="post">
                <h2>Use a local account to log in.</h2>
                <hr />
                <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
                    <label asp-for="Input.Email" class="form-label">Email</label>
                    <span asp-validation-for="Input.Email" class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" placeholder="password" />
                    <label asp-for="Input.Password" class="form-label">Password</label>
                    <span asp-validation-for="Input.Password" class="text-danger"></span>
                </div>
                <div>
                    <button id="login-submit" type="submit" class="w-100 btn btn-lg btn-primary">Log in</button>
                </div>
            </form>
        </div>
        <div class="col-md-4" v-if="loginType == 'AD'">
            <form v-on:submit.prevent="ldapLogin" id="login" method="post">
                <h2>Use a AD account to log in.</h2>
                <hr />
                <div  class="text-danger" role="alert"></div>
                <div class="form-floating mb-3">
                    <input v-model="ldapLoginInfo.username" id="ldapUsername" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
                    <label id="ldapEmailLabel"  class="form-label">Windows Login</label>
                    <span id="ldapEmailError"  class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input v-model="ldapLoginInfo.password" id="ldapPassword" class="form-control" type="password" autocomplete="current-password" aria-required="true" placeholder="password" />
                    <label id="ldapPasswordLabel"  class="form-label">Password</label>
                    <span id="ldapPasswordError"  class="text-danger"></span>
                </div>
                <div>
                    <button id="ldap-login-submit" type="submit" class="w-100 btn btn-lg btn-primary">Log in</button>
                </div>
            </form>
        </div>
        <div class="col-md-6 col-md-offset-2">
            <section>
                <h3>Use another service to log in.</h3>
                <hr />
                @{
                    if ((Model.ExternalLogins?.Count ?? 0) == 0)
                    {
                        <div>
                            <p>
                                There are no external authentication services configured. See this <a href="https://go.microsoft.com/fwlink/?LinkID=532715">article
                                about setting up this ASP.NET application to support logging in via external services</a>.
                            </p>
                        </div>
                    }
                    else
                    {
                        <form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                            <div>
                                <p>
                                    @foreach (var provider in Model.ExternalLogins!)
                                    {
                                        <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                                    }
                                </p>
                            </div>
                        </form>
                    }
                }
            </section>
        </div>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />

    <script>

        $(function () {
            app.mount('#systemLogin');

            $('.closeModal').on('click', function () {
                $('.modal').modal('hide');
            });
        });

        const app = Vue.createApp({
            data() {
                return {
                    loginType: 'AD',
                    ldapLoginInfo: {
                        username: '',
                        password: '',
                    },
                };
            },
            mounted() {

            },
            watch: {

            },
            methods: {
                async ldapLogin() {
                    try {
                        // Show the loading modal
                        $('#loadingModal').modal('show');

                        // Perform the fetch request
                        const response = await fetch('/IdentityAPI/LdapLogin', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(this.ldapLoginInfo),
                        });

                        // Check if the response is OK
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.message);
                        }

                        const data = await response.json();

                        // Redirect if a URL is provided
                        if (data.redirectUrl) {
                            window.location.href = data.redirectUrl;
                        } else {
                            console.error('Login failed:', data);
                            alert('Login failed.');
                        }
                    }
                    catch (error) {
                        console.error('Error during LDAP login:', error);
                        alert(error.message);
                    }
                    finally {
                        await new Promise(resolve => {
                            $('#loadingModal').on('shown.bs.modal', resolve);
                        });
                        $('#loadingModal').modal('hide');
                    }
                },
                async fetchControllerMethodList() {
                    try {
                        const response = await fetch('/AdminAPI/GetListClassAndMethodInformation', {
                            method: 'POST',
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }

                        const data = await response.json();

                        // Assign data if it exists
                        if (data) {
                            this.controllerMethodData = data;
                        }
                    } catch (error) {
                        console.error('There was a problem with the fetch operation:', error);
                    }
                },

            },
        });
    </script>
}
