1+ using System . Windows . Input ;
2+ using HttpGamepadInput . BaseClasses ;
3+
4+ namespace HttpGamepadInput . ViewModels ;
5+
6+ public class SettingsViewModel : BindableBase
7+ {
8+ public ICommand SaveCommand { get ; }
9+ public ICommand TestConnectionCommand { get ; }
10+
11+ private string _serverUrl = "http://localhost:8080" ;
12+ public string ServerUrl
13+ {
14+ get => _serverUrl ;
15+ set => SetProperty ( ref _serverUrl , value ) ;
16+ }
17+
18+ private bool _isNotError = true ;
19+ public bool IsNotError
20+ {
21+ get => _isNotError ;
22+ set => SetProperty ( ref _isNotError , value ) ;
23+ }
24+
25+ private string _validationMessage ;
26+ public string ValidationMessage
27+ {
28+ get => _validationMessage ;
29+ set
30+ {
31+ if ( _validationMessage != value )
32+ {
33+ _validationMessage = value ;
34+ OnPropertyChanged ( ) ;
35+ }
36+ }
37+ }
38+
39+ public SettingsViewModel ( )
40+ {
41+ SaveCommand = new Command ( OnSaveClicked ) ;
42+ TestConnectionCommand = new Command ( OnTestConnectionClicked ) ;
43+ }
44+
45+ private bool IsValidUrl ( string url )
46+ {
47+ if ( string . IsNullOrWhiteSpace ( ServerUrl ) )
48+ {
49+ ValidationMessage = "URL can't be empty." ;
50+ IsNotError = false ;
51+ return false ;
52+ }
53+ else if ( ! Uri . TryCreate ( ServerUrl , UriKind . Absolute , out var uri ) ||
54+ ! ( uri . Scheme == Uri . UriSchemeHttp || uri . Scheme == Uri . UriSchemeHttps ) )
55+ {
56+ ValidationMessage = "Enter valid url address (http or https)." ;
57+ IsNotError = false ;
58+ return false ;
59+ }
60+ else
61+ {
62+ ValidationMessage = string . Empty ; // All Ok
63+ IsNotError = true ;
64+ }
65+ return true ;
66+ }
67+
68+ private void OnSaveClicked ( )
69+ {
70+ string url = ServerUrl . Trim ( ) ;
71+
72+ if ( ! IsValidUrl ( url ) )
73+ {
74+ return ;
75+ }
76+
77+ Preferences . Set ( "ServerUrl" , url ) ;
78+ }
79+
80+ private async void OnTestConnectionClicked ( )
81+ {
82+ string url = ServerUrl . Trim ( ) ;
83+
84+ if ( ! IsValidUrl ( url ) )
85+ {
86+ return ;
87+ }
88+
89+ if ( ! Uri . TryCreate ( url , UriKind . Absolute , out var baseUri ) )
90+ {
91+ ValidationMessage = "Error: Filed creating Uri." ;
92+ IsNotError = false ;
93+ return ;
94+ }
95+
96+ try
97+ {
98+ var versionUri = new Uri ( baseUri , "/version/" ) ;
99+
100+ using HttpClient client = new HttpClient
101+ {
102+ Timeout = TimeSpan . FromSeconds ( 5 )
103+ } ;
104+
105+ HttpResponseMessage response = await client . GetAsync ( versionUri ) ;
106+ if ( response . IsSuccessStatusCode )
107+ {
108+ ValidationMessage = "Success! Connection to the server established." ;
109+ IsNotError = true ;
110+ }
111+ else
112+ {
113+ ValidationMessage = $ "Error. Server response: { ( int ) response . StatusCode } { response . ReasonPhrase } ";
114+ IsNotError = false ;
115+ }
116+ }
117+ catch ( Exception ex )
118+ {
119+ ValidationMessage = $ "Error. Failed to connect: { ex . Message } ";
120+ IsNotError = false ;
121+ }
122+ }
123+ }
0 commit comments