1
0

76 lines
2.1 KiB
C#

using System;
using System.Reactive;
using System.Threading.Tasks;
using Flawless.Client.Remote;
using ReactiveUI;
using ReactiveUI.SourceGenerators;
using Refit;
namespace Flawless.Client.ViewModels;
public partial class LoginViewModel : UserControlViewModelBase
{
[Reactive] private string _username = String.Empty;
[Reactive] private string _password = String.Empty;
[Reactive] private string _issue = String.Empty;
private MainWindowViewModel _main;
public ReactiveCommand<Unit, Unit> LoginCommand { get; }
public ReactiveCommand<Unit, Unit> RegisterCommand { get; }
public ReactiveCommand<Unit, Unit> ChooseServerCommand { get; }
public LoginViewModel(MainWindowViewModel main)
{
_main = main;
Title = $"Login into '{ApiHelper.ServerUrl}'";
var canLogin = this.WhenAnyValue(
x => x.Username,
x => x.Password,
(user, pass) => !string.IsNullOrEmpty(user) && user.Length > 3 && !string.IsNullOrEmpty(pass) && pass.Length >= 6
);
LoginCommand = ReactiveCommand.CreateFromTask(OnLoginAsync, canLogin);
RegisterCommand = ReactiveCommand.Create(OnRegister);
ChooseServerCommand = ReactiveCommand.Create(OnChooseServer);
}
private void OnChooseServer()
{
_main.RedirectToServerSetup();
}
private void OnRegister()
{
throw new NotImplementedException();
}
private async Task OnLoginAsync()
{
try
{
ApiHelper.Token = await ApiHelper.Gateway.Login(new LoginRequest
{
Username = _username,
Password = _password
});
}
catch (ApiException ex)
{
await Console.Error.WriteLineAsync($"Login as '{Username}' Failed: {ex.Content}");
Issue = ex.Content ?? String.Empty;
}
catch (Exception ex)
{
await Console.Error.WriteLineAsync($"Login as '{Username}' Failed: {ex}");
Issue = ex.Message;
}
Console.WriteLine($"Login as '{Username}' success!");
}
}