// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using SelmoStudio.Hmi.Plugin.Model.RestApi;
using SelmoStudio.Hmi.Plugin.Services;
using SelmoStudio.Hmi.Server.SelmoHmi.Authentication.Service;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.WellKnownTypes;
using SelmoStudio.Hmi.Server.Shared.Resources;

namespace SelmoStudio.Hmi.Server.SelmoHmi.Authentication.Components
{
    public partial class AuthenticationComponent
    {
        [Parameter]
        public EventCallback OnAuthenticated { get; set; }

        [Inject]
        private IPluginAuthenticationService _pluginAuthenticationService { get; set; }

        [Inject]
        private IAuthenticationStateService _authenticationStateService { get; set; }

        private bool _userIsLoggedIn { get; set; }

        private WellKnownContentFlexDirection _contentFlexDirection = WellKnownContentFlexDirection.Row;

        private string _username;
        private string _password;
        private string _loginResultMessage;

        private bool isLoginButtonDisabled => string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password);

        private void UpdateUsername(string value)
        {
            _username = value;
        }

        private void UpdatePassword(string value)
        {
            _password = value;
        }

        protected override async Task OnInitializedAsync()
        {
            await CheckIfUserIsLoggedIn();

            await base.OnInitializedAsync();
        }

        private async Task CheckIfUserIsLoggedIn()
        {
            _userIsLoggedIn = await _authenticationStateService.IsAuthenticatedAsync();
        }

        private async Task Login()
        {
            var loginResult = await _pluginAuthenticationService.InternalLogin(new LoginRequest() { Username = _username, Password = _password });

            // TODO Get the type of result that could be checked for faultiness
            if (!string.IsNullOrEmpty(loginResult) && !loginResult.StartsWith("System.ArgumentException"))
            {
                await OnAuthenticated.InvokeAsync();
            }
            else
            {
                _loginResultMessage = _localizer[nameof(HmiResource.AuthenticationNotSuccessful)];
            }
        }

        private async Task Logout()
        {
            var user = await _authenticationStateService.GetCurrentUserAsync();

            await _pluginAuthenticationService.InternalLogout(new LogoutRequest() { Username = user.Identity?.Name, Password = "" });

            await OnAuthenticated.InvokeAsync();
        }
    }
}