namespace HistoryView.ViewModels;

partial class LoginViewModel : ObservableObject
{
    public LoginViewModel(IEventAggregator eventAggregator, LanguageLoader language, UserInformation userInfo, HubSender hubSender)
    {
        this._sender = hubSender;
        this._eventAggregator = eventAggregator;
        this.LanguageLoader = language;
        this.UserInfo = userInfo;
    }

    private readonly IEventAggregator _eventAggregator;
    private readonly HubSender _sender;

    [ObservableProperty]
    private UserInformation _UserInfo;

    [ObservableProperty]
    private LanguageLoader _LanguageLoader;

    [RelayCommand]
    private void ReadOnlyLogin()
    {
        this.Hint = string.Empty;
        this.UserInfo.UserName = (string)App.Current.Resources["DefaultUser"];
        this.UserInfo.Authority = UserAuthority.Guest;
        _eventAggregator.GetEvent<WindowSwitch>().Page = Pages.MainWindow;
        _eventAggregator.GetEvent<WindowSwitch>().Publish();
    }

    [RelayCommand]
    private void Login()
    {
        if (string.IsNullOrEmpty(this.UserInfo.UserName) || string.IsNullOrEmpty(this.UserInfo.Password))
        {
            this.Hint = "User Info Error";
            return;
        }

        if (!this._sender.RequestLogin(this.UserInfo.UserName, this.UserInfo.Password.ToBase64(), out UserAuthority authority))
        {
            this.Hint = "Connection failed";
            return;
        }

        switch (authority)
        {
            case UserAuthority.Deinded:
                this.Hint = "Access Deinde";
                return;
            case UserAuthority.Failed:
            default:
                this.Hint = "Login Failed";
                return;
            case UserAuthority.Guest:
            case UserAuthority.Operator:
            case UserAuthority.Engineer:
            case UserAuthority.God:
                this.Hint = string.Empty;
                this.UserInfo.Authority = authority;
                this.UserInfo.Password = string.Empty;

                _eventAggregator.GetEvent<WindowSwitch>().Page = Pages.MainWindow;
                _eventAggregator.GetEvent<WindowSwitch>().Publish();
                break;
        }

        return;
    }

    [ObservableProperty]
    private string? _hint;
}
