aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Client/mod/scripts/vscripts/ui/menu_ns_serverbrowser.nut
blob: 29c7621c2f5d7db694d0ab7a14d547093824fe7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
untyped
// Only way to get Hud_GetPos(sliderButton) working was to use untyped

global function AddNorthstarServerBrowserMenu
global function ThreadedAuthAndConnectToServer

global function AddConnectToServerCallback
global function RemoveConnectToServerCallback
global function TriggerConnectToServerCallbacks

// Stop peeking

const int BUTTONS_PER_PAGE = 15 // Number of servers we show
const float DOUBLE_CLICK_TIME_MS = 0.4 // Max time between clicks for double click registering 

// Stores mouse delta used for scroll bar
struct {
	int deltaX = 0
	int deltaY = 0
} mouseDeltaBuffer

// Filters
struct {
	bool hideFull = false
	bool hideEmpty = false
	bool hideProtected = false
	bool useSearch = false
	string searchTerm
	array<string> filterMaps
	string filterMap
	array<string> filterGamemodes
	string filterGamemode
} filterArguments


enum sortingBy
{
	NONE,
	DEFAULT,
	NAME,
	PLAYERS,
	MAP,
	GAMEMODE,
	REGION
}

// Column sort direction, only one of these can be aplied at once
struct {
	// true = alphabeticaly false = reverse
	bool serverName = true
	bool serverPlayers = true
	bool serverMap = true
	bool serverGamemode = true
	bool serverRegion = true
	// 0 = none; 1 = default; 2 = name; 3 = players; 4 = map; 5 = gamemode; 6 = region
	int sortingBy = 1
} filterDirection

struct serverStruct {
	int serverIndex
	bool serverProtected
	string serverName
	int serverPlayers
	int serverPlayersMax
	string serverMap
	string serverGamemode
	string serverRegion
}

struct {
	// UI state vars
	var menu
	int focusedServerIndex = 0
	int scrollOffset = 0
	bool serverListRequestFailed = false
	float serverSelectedTime = 0
	float serverSelectedTimeLast = 0
	int serverButtonFocusedID = 0
	bool shouldFocus = true
	bool cancelConnection = false
	
	// filtered array of servers
	array<serverStruct> serversArrayFiltered

	array<ServerInfo> filteredServers
	ServerInfo& focusedServer
	ServerInfo& lastSelectedServer
	
	// UI references
	array<var> serverButtons
	array<var> serversName
	array<var> playerCountLabels
	array<var> serversProtected
	array<var> serversMap
	array<var> serversGamemode
	array<var> serversRegion

	array< void functionref( ServerInfo ) > connectCallbacks
} file



bool function FloatsEqual( float arg1, float arg2, float epsilon )
{
	if ( fabs( arg1 - arg2 ) < epsilon ) return true
	
	return false
}


////////////////////////////
// Init
////////////////////////////
void function AddNorthstarServerBrowserMenu()
{
	AddMenu( "ServerBrowserMenu", $"resource/ui/menus/server_browser.menu", InitServerBrowserMenu, "#MENU_SERVER_BROWSER" )
}

void function UpdatePrivateMatchModesAndMaps()
{
	array<string> realMaps = [ "mp_lobby" ]
	realMaps.extend( GetPrivateMatchMaps() )

	foreach ( int enum_, string map in realMaps )
	{
		if ( filterArguments.filterMaps.find( map ) != -1 )
			continue

		filterArguments.filterMaps.append( map )

		string localized = GetMapDisplayName( map )
		Hud_DialogList_AddListItem( Hud_GetChild( file.menu, "SwtBtnSelectMap" ) , localized, string( enum_ + 1 ) )
	}

	array<string> realModes = [ "private_match" ]
	realModes.extend( GetPrivateMatchModes() )

	foreach( int enum_, string mode in realModes )
	{
		string localized = GetGameModeDisplayName( mode )
		if ( filterArguments.filterGamemodes.find( localized ) != -1 )
			continue

		filterArguments.filterGamemodes.append( localized )
		Hud_DialogList_AddListItem( Hud_GetChild( file.menu, "SwtBtnSelectGamemode" ) , localized, string( enum_ + 1 ) )
	}
}

void function InitServerBrowserMenu()
{
	file.menu = GetMenu( "ServerBrowserMenu" )

	AddMouseMovementCaptureHandler( Hud_GetChild(file.menu, "MouseMovementCapture"), UpdateMouseDeltaBuffer )

	// Get menu stuff
	file.serverButtons = GetElementsByClassname( file.menu, "ServerButton" )
	file.serversName = GetElementsByClassname( file.menu, "ServerName" )
	file.playerCountLabels = GetElementsByClassname( file.menu, "PlayerCount" )
	file.serversProtected = GetElementsByClassname( file.menu, "ServerLock" )
	file.serversMap = GetElementsByClassname( file.menu, "ServerMap" )
	file.serversGamemode = GetElementsByClassname( file.menu, "ServerGamemode" )
	file.serversRegion = GetElementsByClassname( file.menu, "Serverregion" )

	filterArguments.filterMaps = [ "SWITCH_ANY" ]
	Hud_DialogList_AddListItem( Hud_GetChild( file.menu, "SwtBtnSelectMap" ), "SWITCH_ANY", "0" )

	filterArguments.filterGamemodes = [ "SWITCH_ANY" ]
	Hud_DialogList_AddListItem( Hud_GetChild( file.menu, "SwtBtnSelectGamemode" ), "SWITCH_ANY", "0" )

	// Event handlers
	AddMenuEventHandler( file.menu, eUIEvent.MENU_CLOSE, OnCloseServerBrowserMenu )
	AddMenuEventHandler( file.menu, eUIEvent.MENU_OPEN, OnServerBrowserMenuOpened )
	AddMenuFooterOption( file.menu, BUTTON_B, "#B_BUTTON_BACK", "#BACK" )
	AddMenuFooterOption( file.menu, BUTTON_Y, PrependControllerPrompts( BUTTON_Y, "#REFRESH_SERVERS" ), "#REFRESH_SERVERS", RefreshServers )

	// Setup server buttons
	var width = 1120.0  * ( GetScreenSize()[1] / 1080.0 )
	foreach ( var button in GetElementsByClassname( file.menu, "ServerButton" ) )
	{
		AddButtonEventHandler( button, UIE_CLICK, OnServerButtonClicked )
		AddButtonEventHandler( button, UIE_GET_FOCUS, OnServerButtonFocused )
		Hud_SetWidth( button , width )
	}

	AddButtonEventHandler( Hud_GetChild( file.menu , "BtnServerDummmyTop" ), UIE_GET_FOCUS, OnHitDummyTop )
	AddButtonEventHandler( Hud_GetChild( file.menu , "BtnServerDummmyBottom" ), UIE_GET_FOCUS, OnHitDummyBottom )



	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerJoin"), UIE_CLICK, OnServerSelected )

	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerListUpArrow"), UIE_CLICK, OnUpArrowSelected )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerListDownArrow"), UIE_CLICK, OnDownArrowSelected )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnDummyAfterFilterClear"), UIE_GET_FOCUS, OnHitDummyAfterFilterClear )



	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnFiltersClear"), UIE_CLICK, OnBtnFiltersClear_Activate )


	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerNameTab"), UIE_CLICK, SortServerListByName_Activate )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerPlayersTab"), UIE_CLICK, SortServerListByPlayers_Activate )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerMapTab"), UIE_CLICK, SortServerListByMap_Activate )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerGamemodeTab"), UIE_CLICK, SortServerListByGamemode_Activate )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerRegionTab"), UIE_CLICK, SortServerListByRegion_Activate )


	AddButtonEventHandler( Hud_GetChild( file.menu, "SwtBtnSelectMap"), UIE_CHANGE, FilterAndUpdateList )
	AddButtonEventHandler( Hud_GetChild( file.menu, "SwtBtnSelectGamemode"), UIE_CHANGE, FilterAndUpdateList )
	AddButtonEventHandler( Hud_GetChild( file.menu, "SwtBtnHideFull"), UIE_CHANGE, FilterAndUpdateList )
	AddButtonEventHandler( Hud_GetChild( file.menu, "SwtBtnHideEmpty"), UIE_CHANGE, FilterAndUpdateList )
	AddButtonEventHandler( Hud_GetChild( file.menu, "SwtBtnHideProtected"), UIE_CHANGE, FilterAndUpdateList )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnSearchLabel"), UIE_CHANGE, FilterAndUpdateList )

	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerSearch"), UIE_CHANGE, FilterAndUpdateList )

	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerDescription"), UIE_CLICK, ShowServerDescription )
	AddButtonEventHandler( Hud_GetChild( file.menu, "BtnServerMods"), UIE_CLICK, ShowServerMods )

	AddButtonEventHandler( Hud_GetChild( file.menu, "ConnectingButton"), UIE_CLICK, ConnectingButton_Activate )


	// Hidden cause no need, if server descriptions become too long use this
	Hud_SetEnabled( Hud_GetChild( file.menu, "BtnServerDescription"), false )
	Hud_SetEnabled( Hud_GetChild( file.menu, "BtnServerMods"), false )
	Hud_SetText( Hud_GetChild( file.menu, "BtnServerDescription"), "" )
	Hud_SetText( Hud_GetChild( file.menu, "BtnServerMods"), "" )


	// Rui is a pain
	RuiSetString( Hud_GetRui( Hud_GetChild( file.menu, "SwtBtnHideFull") ), "buttonText", "" )
	RuiSetString( Hud_GetRui( Hud_GetChild( file.menu, "SwtBtnHideEmpty") ), "buttonText", "" )
	RuiSetString( Hud_GetRui( Hud_GetChild( file.menu, "SwtBtnHideProtected") ), "buttonText", "" )
	RuiSetString( Hud_GetRui( Hud_GetChild( file.menu, "SwtBtnSelectMap") ), "buttonText", "" )
	RuiSetString( Hud_GetRui( Hud_GetChild( file.menu, "SwtBtnSelectGamemode") ), "buttonText", "" )


	ToggleConnectingHUD(false)

	// UI was cut off on some aspect ratios; not perfect
	UpdateServerInfoBasedOnRes()
}

////////////////////////////
// Slider
////////////////////////////
void function UpdateMouseDeltaBuffer( int x, int y )
{
	mouseDeltaBuffer.deltaX += x
	mouseDeltaBuffer.deltaY += y

	SliderBarUpdate()
}

void function FlushMouseDeltaBuffer()
{
	mouseDeltaBuffer.deltaX = 0
	mouseDeltaBuffer.deltaY = 0
}


void function SliderBarUpdate()
{
	if ( file.filteredServers.len() <= BUTTONS_PER_PAGE )
	{
		FlushMouseDeltaBuffer()
		return
	}

	var sliderButton = Hud_GetChild( file.menu , "BtnServerListSlider" )
	var sliderPanel = Hud_GetChild( file.menu , "BtnServerListSliderPanel" )
	var movementCapture = Hud_GetChild( file.menu , "MouseMovementCapture" )

	Hud_SetFocused( sliderButton )

	float minYPos = -40.0 * ( GetScreenSize()[1] / 1080.0 )
	float maxHeight = 562.0  * ( GetScreenSize()[1] / 1080.0 )
	float maxYPos = minYPos - ( maxHeight - Hud_GetHeight( sliderPanel ) )
	float useableSpace = ( maxHeight - Hud_GetHeight( sliderPanel ) )

	float jump = minYPos - ( useableSpace / ( float( file.filteredServers.len() ) ) )

	// got local from official respaw scripts, without untyped throws an error
	local pos =	Hud_GetPos( sliderButton )[1]
	local newPos = pos - mouseDeltaBuffer.deltaY
	FlushMouseDeltaBuffer()

	if ( newPos < maxYPos ) newPos = maxYPos
	if ( newPos > minYPos ) newPos = minYPos

	Hud_SetPos( sliderButton , 2, newPos )
	Hud_SetPos( sliderPanel , 2, newPos )
	Hud_SetPos( movementCapture , 2, newPos )

	file.scrollOffset = -int( ( ( newPos - minYPos ) / useableSpace ) * ( file.filteredServers.len() - BUTTONS_PER_PAGE ) )
	UpdateShownPage()
}

void function UpdateListSliderHeight( float servers )
{
	var sliderButton = Hud_GetChild( file.menu , "BtnServerListSlider" )
	var sliderPanel = Hud_GetChild( file.menu , "BtnServerListSliderPanel" )
	var movementCapture = Hud_GetChild( file.menu , "MouseMovementCapture" )

	float maxHeight = 562.0 * ( GetScreenSize()[1] / 1080.0 )
	float minHeight = 80.0 * ( GetScreenSize()[1] / 1080.0 )

	float height = maxHeight * ( BUTTONS_PER_PAGE / servers )

	if ( height > maxHeight ) height = maxHeight
	if ( height < minHeight ) height = minHeight

	Hud_SetHeight( sliderButton , height )
	Hud_SetHeight( sliderPanel , height )
	Hud_SetHeight( movementCapture , height )
}


void function UpdateListSliderPosition( int servers )
{
	var sliderButton = Hud_GetChild( file.menu , "BtnServerListSlider" )
	var sliderPanel = Hud_GetChild( file.menu , "BtnServerListSliderPanel" )
	var movementCapture = Hud_GetChild( file.menu , "MouseMovementCapture" )

	float minYPos = -40.0 * ( GetScreenSize()[1] / 1080.0 )
	float useableSpace = (562.0 * ( GetScreenSize()[1] / 1080.0 ) - Hud_GetHeight( sliderPanel ) )

	float jump = minYPos - ( useableSpace / ( float( servers ) - BUTTONS_PER_PAGE ) * file.scrollOffset )

	if ( jump > minYPos ) jump = minYPos

	Hud_SetPos( sliderButton , 2, jump )
	Hud_SetPos( sliderPanel , 2, jump )
	Hud_SetPos( movementCapture , 2, jump )
}

void function OnScrollDown( var button )
{
	if (file.filteredServers.len() <= BUTTONS_PER_PAGE) return
	file.scrollOffset += 5
	if (file.scrollOffset + BUTTONS_PER_PAGE > file.filteredServers.len()) {
		file.scrollOffset = file.filteredServers.len() - BUTTONS_PER_PAGE
	}
	UpdateShownPage()
	UpdateListSliderPosition( file.filteredServers.len() )
}

void function OnScrollUp( var button )
{
	file.scrollOffset -= 5
	if ( file.scrollOffset < 0 ) {
		file.scrollOffset = 0
	}
	UpdateShownPage()
	UpdateListSliderPosition( file.filteredServers.len() )
}

////////////////////////////
// Connecting pop-up
////////////////////////////
void function ToggleConnectingHUD( bool vis )
{
	foreach (e in GetElementsByClassname( file.menu, "connectingHUD" ) ) {
		Hud_SetEnabled( e, vis )
		Hud_SetVisible( e, vis )
	}

	if ( vis ) Hud_SetFocused( Hud_GetChild( file.menu, "ConnectingButton" ) )
}

void function ConnectingButton_Activate( var button )
{
	file.cancelConnection = true
}

////////////////////////////
// Aspect ratio compensation
////////////////////////////
// No way to get aspect ratio sadly
// This doesn't werk on some obscure resolutions, mostly really small 4:3
void function UpdateServerInfoBasedOnRes()
{
	if ( FloatsEqual( float(GetScreenSize()[0] ) / float( GetScreenSize()[1] ) , 1.6, 0.07 ) ) // 16/10
	{
		Hud_SetWidth( Hud_GetChild(file.menu, "ServerName"), 392)
		Hud_SetWidth( Hud_GetChild(file.menu, "NextMapImage"), 400)
		Hud_SetWidth( Hud_GetChild(file.menu, "NextMapBack"), 400)
		Hud_SetWidth( Hud_GetChild(file.menu, "LabelMods"), 360)
		Hud_SetWidth( Hud_GetChild(file.menu, "LabelDescription"), 360)
		Hud_SetWidth( Hud_GetChild(file.menu, "ServerDetailsPanel"), 400)
	}
	if( FloatsEqual( float( GetScreenSize()[0] ) / float( GetScreenSize()[1] ) , 1.3, 0.055 ) ) // 4/3
	{
		Hud_SetWidth( Hud_GetChild(file.menu, "ServerName"), 292)
		Hud_SetWidth( Hud_GetChild(file.menu, "NextMapImage"), 300)
		Hud_SetWidth( Hud_GetChild(file.menu, "NextMapBack"), 300)
		Hud_SetWidth( Hud_GetChild(file.menu, "LabelMods"), 260)
		Hud_SetWidth( Hud_GetChild(file.menu, "LabelDescription"), 260)
		Hud_SetWidth( Hud_GetChild(file.menu, "ServerDetailsPanel"), 300)
	}
}

////////////////////////////
// Open/close callbacks
////////////////////////////
void function OnCloseServerBrowserMenu()
{
	try
	{
		DeregisterButtonPressedCallback( MOUSE_WHEEL_UP , OnScrollUp )
		DeregisterButtonPressedCallback( MOUSE_WHEEL_DOWN , OnScrollDown )
		DeregisterButtonPressedCallback( KEY_TAB , OnKeyTabPressed )
		DeregisterButtonPressedCallback( KEY_ENTER, OnEnterPressed )
		DeregisterButtonPressedCallback( KEY_R, OnKeyRPressed )
	}
	catch ( ex ) {}
}

void function OnServerBrowserMenuOpened()
{
	Hud_SetText( Hud_GetChild( file.menu, "InGamePlayerLabel" ), Localize( "#INGAME_PLAYERS", "0" ) )
	Hud_SetText( Hud_GetChild( file.menu, "TotalServerLabel" ),  Localize( "#TOTAL_SERVERS", "0" ) )
	UpdatePrivateMatchModesAndMaps()
	Hud_SetText( Hud_GetChild( file.menu, "Title" ), "#MENU_TITLE_SERVER_BROWSER" )
	UI_SetPresentationType( ePresentationType.KNOWLEDGEBASE_MAIN )

	file.scrollOffset = 0
	// dont rerequest if we came from the connect menu
	if ( !NSIsRequestingServerList() && uiGlobal.lastMenuNavDirection != MENU_NAV_BACK )
	{
		NSClearRecievedServerList()
		NSRequestServerList()
	}

	filterDirection.sortingBy = sortingBy.DEFAULT

	thread WaitForServerListRequest()


	RegisterButtonPressedCallback( MOUSE_WHEEL_UP , OnScrollUp )
	RegisterButtonPressedCallback( MOUSE_WHEEL_DOWN , OnScrollDown )
	RegisterButtonPressedCallback( KEY_TAB , OnKeyTabPressed )
	RegisterButtonPressedCallback( KEY_ENTER, OnEnterPressed )
	RegisterButtonPressedCallback( KEY_R, OnKeyRPressed )
}

////////////////////////////
// Arrow navigation fuckery
////////////////////////////
bool function IsFilterPanelElementFocused()
{
	// get name of focused element
	var focusedElement = GetFocus()

	foreach ( element in GetElementsByClassname( file.menu, "FilterPanelChild" ) )
	{
		if ( element == focusedElement ) return true
	}


	return false;
}

void function OnKeyTabPressed( var button )
{
	try
	{
		// toggle focus between server list and filter panel
		if ( IsFilterPanelElementFocused() )
		{
			Hud_SetFocused( Hud_GetChild( file.menu, "BtnServer1" ) )
		}
		else
		{
			Hud_SetFocused( Hud_GetChild( file.menu, "BtnServerSearch" ) )
			HideServerInfo()
		}
	}
	catch ( ex ) {}
}

void function OnHitDummyTop( var button )
{
	file.scrollOffset -= 1
	if ( file.scrollOffset < 0 )
	{
		// was at top already
		file.scrollOffset = 0
		Hud_SetFocused(Hud_GetChild(file.menu, "BtnServerNameTab"))
	}
	else 
	{
		// only update if list position changed
		UpdateShownPage()
		UpdateListSliderPosition( file.filteredServers.len() )
		DisplayFocusedServerInfo( file.serverButtonFocusedID )
		Hud_SetFocused( Hud_GetChild( file.menu, "BtnServer1" ) )
	}
}

void function OnHitDummyBottom( var button )
{
	file.scrollOffset += 1
	if ( file.scrollOffset + BUTTONS_PER_PAGE > file.filteredServers.len() )
	{
		// was at bottom already
		file.scrollOffset = file.filteredServers.len() - BUTTONS_PER_PAGE
		Hud_SetFocused( Hud_GetChild( file.menu, "BtnServerSearch" ) )
		HideServerInfo()
	}
	else
	{
		// only update if list position changed
		UpdateShownPage()
		UpdateListSliderPosition( file.filteredServers.len() )
		DisplayFocusedServerInfo( file.serverButtonFocusedID )
		Hud_SetFocused( Hud_GetChild( file.menu, "BtnServer15" ) )
	}
}

void function OnHitDummyAfterFilterClear( var button )
{
	Hud_SetFocused( Hud_GetChild( file.menu, "BtnServerNameTab" ) )
}


void function OnDownArrowSelected( var button )
{
	if ( file.filteredServers.len() <= BUTTONS_PER_PAGE ) return
	file.scrollOffset += 1
	if ( file.scrollOffset + BUTTONS_PER_PAGE > file.filteredServers.len() )
	{
		file.scrollOffset = file.filteredServers.len() - BUTTONS_PER_PAGE
	}
	
	UpdateShownPage()
	UpdateListSliderPosition( file.filteredServers.len() )
}


void function OnUpArrowSelected( var button )
{
	file.scrollOffset -= 1
	if ( file.scrollOffset < 0 )
	{
		file.scrollOffset = 0
	}
	
	UpdateShownPage()
	UpdateListSliderPosition( file.filteredServers.len() )
}

////////////////////////
// Key Callbacks
////////////////////////
void function OnEnterPressed( arg ) 
{
	// only trigger if a server is focused
	if ( IsServerButtonFocused() ) 
	{
		OnServerSelected(0)
	}
}

void function OnKeyRPressed( arg ) 
{
	if ( !IsSearchBarFocused() ) 
	{
		RefreshServers(0);
	}
}

bool function IsServerButtonFocused() 
{
	var focusedElement = GetFocus()
	if ( focusedElement == null )
		return false
	
	var name = Hud_GetHudName( focusedElement )

	foreach ( element in GetElementsByClassname( file.menu, "ServerButton" ) ) 
	{
		if ( element == focusedElement ) 
			return true
	}

	return false
}

bool function IsSearchBarFocused() 
{
	return Hud_GetChild( file.menu, "BtnServerSearch" ) == GetFocus()
}


////////////////////////////
// Unused
////////////////////////////
void function ShowServerDescription( var button )
{
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelDescription" ), true )
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelMods" ), false )
}

void function ShowServerMods( var button )
{
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelDescription" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelMods" ), true )
}

////////////////////////////
// Server list; filter,update,...
////////////////////////////
void function HideServerInfo()
{
	Hud_SetVisible( Hud_GetChild( file.menu, "BtnServerDescription" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "BtnServerMods" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "BtnServerJoin" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelDescription" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "LabelMods" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "NextMapImage" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "NextMapBack" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "NextMapName" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "ServerName" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "NextModeIcon" ), false )
	Hud_SetVisible( Hud_GetChild( file.menu, "NextGameModeName" ), false )
}

void function OnBtnFiltersClear_Activate( var button )
{
	Hud_SetText( Hud_GetChild( file.menu, "BtnServerSearch" ), "" )

	SetConVarBool( "filter_hide_empty", false )
	SetConVarBool( "filter_hide_full", false )
	SetConVarBool( "filter_hide_protected", false )
	SetConVarInt( "filter_map", 0 )
	SetConVarInt( "filter_gamemode", 0 )

	FilterAndUpdateList(0)
}

void function FilterAndUpdateList( var n )
{
	filterArguments.searchTerm = Hud_GetUTF8Text( Hud_GetChild( file.menu, "BtnServerSearch" ) )
	if ( filterArguments.searchTerm == "" ) filterArguments.useSearch = false else filterArguments.useSearch = true
	filterArguments.filterMap = filterArguments.filterMaps[ GetConVarInt( "filter_map" ) ]
	filterArguments.filterGamemode = filterArguments.filterGamemodes[ GetConVarInt( "filter_gamemode" ) ]
	filterArguments.hideEmpty = GetConVarBool( "filter_hide_empty" )
	filterArguments.hideFull = GetConVarBool( "filter_hide_full" )
	filterArguments.hideProtected = GetConVarBool( "filter_hide_protected" )

	file.scrollOffset = 0
	UpdateListSliderPosition( file.filteredServers.len() )

	HideServerInfo()
	FilterServerList()


	switch ( filterDirection.sortingBy )
	{
		case sortingBy.NONE:
			UpdateShownPage()
			break
		case sortingBy.DEFAULT:
			filterDirection.serverName = !filterDirection.serverName
			SortServerListByDefault_Activate(0)
			break
		case sortingBy.NAME:
			filterDirection.serverName = !filterDirection.serverName
			SortServerListByName_Activate(0)
			break
		case sortingBy.PLAYERS:
			filterDirection.serverPlayers = !filterDirection.serverPlayers
			SortServerListByPlayers_Activate(0)
			break
		case sortingBy.MAP:
			filterDirection.serverMap = !filterDirection.serverMap
			SortServerListByMap_Activate(0)
			break
		case sortingBy.GAMEMODE:
			filterDirection.serverGamemode = !filterDirection.serverGamemode
			SortServerListByGamemode_Activate(0)
			break
		case sortingBy.REGION:
			filterDirection.serverRegion = !filterDirection.serverRegion
			SortServerListByRegion_Activate(0)
			break
		default:
			printt( "How the f did you get here" )
	}

	if ( file.shouldFocus )
	{
		file.shouldFocus = false
		Hud_SetFocused( Hud_GetChild( file.menu, "BtnServer1" ) )
	}
}


void function RefreshServers( var button )
{
	if ( NSIsRequestingServerList() )
		return

	file.serverListRequestFailed = false
	file.scrollOffset = 0
	NSClearRecievedServerList()
	NSRequestServerList()

	thread WaitForServerListRequest()
}


void function WaitForServerListRequest()
{
	for ( int i = 0; i < BUTTONS_PER_PAGE; i++)
	{
		Hud_SetVisible( file.serversProtected[ i ], false )
		Hud_SetVisible( file.serverButtons[ i ], false )
		Hud_SetText( file.serversName[ i ], "" )
		Hud_SetText( file.playerCountLabels[ i ], "" )
		Hud_SetText( file.serversMap[ i ], "" )
		Hud_SetText( file.serversGamemode[ i ], "" )
		Hud_SetText( file.serversRegion[ i ], "" )
	}

	HideServerInfo()

	Hud_SetVisible( file.serversName[ 0 ], true )
	Hud_SetText( file.serversName[ 0 ], "#NS_SERVERBROWSER_WAITINGFORSERVERS" )

	// wait for request to complete
	while ( NSIsRequestingServerList() )
		WaitFrame()

	file.serverListRequestFailed = !NSMasterServerConnectionSuccessful()
	if ( file.serverListRequestFailed )
	{
		Hud_SetText( file.serversName[ 0 ], "#NS_SERVERBROWSER_CONNECTIONFAILED" )
	}
	else
	{
		FilterAndUpdateList(0)
		Hud_SetFocused( Hud_GetChild(file.menu, "BtnServer1" ) )
	}
}



void function FilterServerList()
{
	file.filteredServers.clear()
	int totalPlayers = 0

	array<ServerInfo> servers = NSGetGameServers()

	foreach ( ServerInfo server in servers )
	{
		totalPlayers += server.playerCount

		// Filters
		if ( filterArguments.hideEmpty && server.playerCount == 0 )
			continue;
		
		if ( filterArguments.hideFull && server.playerCount == server.maxPlayerCount )
			continue;
		
		if ( filterArguments.hideProtected && server.requiresPassword )
			continue;
		
		if ( filterArguments.filterMap != "SWITCH_ANY" && filterArguments.filterMap != server.map )
			continue;
		
		if ( filterArguments.filterGamemode != "SWITCH_ANY" && filterArguments.filterGamemode != GetGameModeDisplayName(server.playlist) )
			continue;
	
		// Search
		if ( filterArguments.useSearch )
		{	
			array<string> sName
			sName.append( server.name.tolower() )
			sName.append( Localize( GetMapDisplayName( server.map ) ).tolower() )
			sName.append( server.map.tolower() )
			sName.append( server.playlist.tolower() )
			sName.append( Localize( server.playlist ).tolower() )
			sName.append( server.description.tolower() )
			sName.append( server.region.tolower() )

			string sTerm = filterArguments.searchTerm.tolower()
			
			bool found = false
			for( int j = 0; j < sName.len(); j++ )
			{
				if ( sName[j].find( sTerm ) != null )
					found = true
			}
			
			if ( !found )
				continue;
		}

		file.filteredServers.append( server )
	}
	
	// Update player and server count
	Hud_SetText( Hud_GetChild( file.menu, "InGamePlayerLabel" ), Localize("#INGAME_PLAYERS", string( totalPlayers ) ) )
	Hud_SetText( Hud_GetChild( file.menu, "TotalServerLabel" ),  Localize("#TOTAL_SERVERS", string( NSGetServerCount() ) ) )
}


void function UpdateShownPage()
{

	for ( int i = 0; i < BUTTONS_PER_PAGE; i++ )
	{
		Hud_SetVisible( file.serversProtected[ i ], false )
		Hud_SetVisible( file.serverButtons[ i ], false )
		Hud_SetText( file.serversName[ i ], "" )
		Hud_SetText( file.playerCountLabels[ i ], "" )
		Hud_SetText( file.serversMap[ i ], "" )
		Hud_SetText( file.serversGamemode[ i ], "" )
		Hud_SetText( file.serversRegion[ i ], "" )
	}

	int j = file.filteredServers.len() > BUTTONS_PER_PAGE ? BUTTONS_PER_PAGE : file.filteredServers.len()

	for ( int i = 0; i < j; i++ )
	{
		int buttonIndex = file.scrollOffset + i
		ServerInfo server = file.filteredServers[ buttonIndex ]

		Hud_SetEnabled( file.serverButtons[ i ], true )
		Hud_SetVisible( file.serverButtons[ i ], true )

		Hud_SetVisible( file.serversProtected[ i ], server.requiresPassword )
		Hud_SetText( file.serversName[ i ], server.name )
		Hud_SetText( file.playerCountLabels[ i ], format( "%i/%i", server.playerCount, server.maxPlayerCount ) )
		Hud_SetText( file.serversMap[ i ], GetMapDisplayName( server.map ) )
		Hud_SetText( file.serversGamemode[ i ], GetGameModeDisplayName( server.playlist ) )
		Hud_SetText( file.serversRegion[ i ], server.region )
	}


	if ( NSGetServerCount() == 0 )
	{
		Hud_SetEnabled( file.serverButtons[ 0 ], true )
		Hud_SetVisible( file.serverButtons[ 0 ], true )
		Hud_SetText( file.serversName[ 0 ], "#NS_SERVERBROWSER_NOSERVERS" )
	}
	UpdateListSliderHeight( float( file.filteredServers.len() ) )
}

void function OnServerButtonFocused( var button )
{
	if ( file.scrollOffset < 0 )
		file.scrollOffset = 0
	
	int scriptID = int ( Hud_GetScriptID( button ) )
	file.serverButtonFocusedID = scriptID
	if ( file.filteredServers.len() > 0 )
		// file.focusedServerIndex = file.filteredServers[ file.scrollOffset + scriptID ].serverIndex
		file.focusedServer = file.filteredServers[ file.scrollOffset + scriptID ]
	DisplayFocusedServerInfo( scriptID )

}

void function OnServerButtonClicked(var button)
{
	int scriptID = int ( Hud_GetScriptID( button ) )

	DisplayFocusedServerInfo( scriptID )
	CheckDoubleClick( scriptID, true )
}

void function CheckDoubleClick( int scriptID, bool wasClickNav )
{
	if ( NSGetServerCount() == 0 ) return


	int serverIndex = file.scrollOffset + scriptID

	bool sameServer = false
	if ( file.lastSelectedServer == file.filteredServers[ serverIndex ] ) sameServer = true

	file.serverSelectedTimeLast = file.serverSelectedTime
	file.serverSelectedTime = Time()

	file.lastSelectedServer = file.filteredServers[ serverIndex ]

	if ( wasClickNav && ( file.serverSelectedTime - file.serverSelectedTimeLast < DOUBLE_CLICK_TIME_MS ) && sameServer )
	{
		OnServerSelected(0)
	}
}

void function DisplayFocusedServerInfo( int scriptID )
{
	if ( scriptID == 999 || scriptID == -1 || scriptID == 16 ) return

	if ( NSIsRequestingServerList() || NSGetServerCount() == 0 || file.serverListRequestFailed || file.filteredServers.len() == 0 )
		return

	var menu = GetMenu( "ServerBrowserMenu" )

	int serverIndex = file.scrollOffset + scriptID
	if ( serverIndex < 0 ) serverIndex = 0

	ServerInfo server = file.filteredServers[ serverIndex ]

	Hud_SetVisible( Hud_GetChild( menu, "BtnServerDescription" ), true )
	Hud_SetVisible( Hud_GetChild( menu, "BtnServerMods" ), true )
	Hud_SetVisible( Hud_GetChild( menu, "BtnServerJoin" ), true )
	// text panels
	Hud_SetVisible( Hud_GetChild( menu, "LabelDescription" ), true )
	Hud_SetVisible( Hud_GetChild( menu, "LabelMods" ), false )
	Hud_SetText( Hud_GetChild( menu, "LabelDescription" ), server.description + "\n\nRequired Mods:\n" + FillInServerModsLabel( server.requiredMods ) )

	// map name/image/server name
	string map = server.map
	Hud_SetVisible( Hud_GetChild( menu, "NextMapImage" ), true )
	Hud_SetVisible( Hud_GetChild( menu, "NextMapBack" ), true )
	RuiSetImage( Hud_GetRui( Hud_GetChild( menu, "NextMapImage" ) ), "basicImage", GetMapImageForMapName( map ) )
	Hud_SetVisible( Hud_GetChild( menu, "NextMapName" ), true )
	Hud_SetText( Hud_GetChild( menu, "NextMapName" ), GetMapDisplayName( map ) )
	Hud_SetVisible( Hud_GetChild( menu, "ServerName" ), true )
	Hud_SetText( Hud_GetChild( menu, "ServerName" ), server.name )

	// mode name/image
	string mode = server.playlist
	Hud_SetVisible( Hud_GetChild( menu, "NextModeIcon" ), true )
	RuiSetImage( Hud_GetRui( Hud_GetChild( menu, "NextModeIcon" ) ), "basicImage", GetPlaylistThumbnailImage( mode ) )
	Hud_SetVisible( Hud_GetChild( menu, "NextGameModeName" ), true )

	if ( mode.len() != 0 )
		Hud_SetText( Hud_GetChild( menu, "NextGameModeName" ), GetGameModeDisplayName( mode ) )
	else
		Hud_SetText( Hud_GetChild( menu, "NextGameModeName" ), "#NS_SERVERBROWSER_UNKNOWNMODE" )
}

string function FillInServerModsLabel( array<RequiredModInfo> mods )
{
	string ret

	foreach ( RequiredModInfo mod in mods )
	{
		ret += format( "  %s v%s\n", mod.name, mod.version )
	}

	return ret
}


void function OnServerSelected( var button )
{
	thread OnServerSelected_Threaded( button )
}

void function OnServerSelected_Threaded( var button )
{
	if ( NSIsRequestingServerList() || NSGetServerCount() == 0 || file.serverListRequestFailed )
		return

	ServerInfo server = file.focusedServer
	file.lastSelectedServer = server

	// Count mods that have been successfully downloaded
	bool autoDownloadAllowed = GetConVarBool( "allow_mod_auto_download" )
	int downloadedMods = 0;

	foreach ( RequiredModInfo mod in server.requiredMods )
	{
		if ( !NSGetModNames().contains( mod.name ) )
		{
			// Check if mod can be auto-downloaded
			bool modIsVerified = NSIsModDownloadable( mod.name, mod.version )

			// Display an error message if not
			if ( !modIsVerified || !autoDownloadAllowed )
			{
				DialogData dialogData
				dialogData.header = "#ERROR"
				dialogData.message = Localize( "#MISSING_MOD", mod.name, mod.version )
				dialogData.image = $"ui/menu/common/dialog_error"

				// Specify error (only if autoDownloadAllowed is set)
				if ( autoDownloadAllowed )
				{
					dialogData.message += "\n" + Localize( "#MOD_NOT_VERIFIED" )
				}

				AddDialogButton( dialogData, "#DISMISS" )

				AddDialogFooter( dialogData, "#A_BUTTON_SELECT" )
				AddDialogFooter( dialogData, "#B_BUTTON_DISMISS_RUI" )

				OpenDialog( dialogData )

				return
			}

			else // Launch download
			{
				if ( DownloadMod( mod ) )
				{
					downloadedMods++
				}
				else
				{
					DisplayModDownloadErrorDialog( mod.name )
					return
				}
			}
		}
		else
		{
			// this uses semver https://semver.org
			array<string> serverModVersion = split( mod.name, "." )
			array<string> clientModVersion = split( NSGetModVersionByModName( mod.name ), "." )

			bool semverFail = false
			// if server has invalid semver don't bother checking
			if ( serverModVersion.len() == 3 )
			{
				// bad client semver
				if ( clientModVersion.len() != serverModVersion.len() )
					semverFail = true
				// major version, don't think we should need to check other versions
				else if ( clientModVersion[ 0 ] != serverModVersion[ 0 ] )
					semverFail = true
			}

			if ( semverFail )
			{
				DialogData dialogData
				dialogData.header = "#ERROR"
				dialogData.message = format( "Server has mod \"%s\" v%s while we have v%s", mod.name, mod.version, NSGetModVersionByModName( mod.name ) )
				dialogData.image = $"ui/menu/common/dialog_error"

				#if PC_PROG
					AddDialogButton( dialogData, "#DISMISS" )

					AddDialogFooter( dialogData, "#A_BUTTON_SELECT" )
				#endif // PC_PROG
				AddDialogFooter( dialogData, "#B_BUTTON_DISMISS_RUI" )

				OpenDialog( dialogData )

				return
			}
		}
	}

	// Make Northstar aware new mods have been added
	if ( downloadedMods > 0 )
	{
		print( "Some new mods have been downloaded or enabled, reloading mods." )
		NSReloadMods();
	}

	if ( server.requiresPassword )
	{
		OnCloseServerBrowserMenu()
		AdvanceMenu( GetMenu( "ConnectWithPasswordMenu" ) )
	}
	else
	{
		TriggerConnectToServerCallbacks()
		thread ThreadedAuthAndConnectToServer()
	}
}


void function ThreadedAuthAndConnectToServer( string password = "" )
{
	if ( NSIsAuthenticatingWithServer() )
		return

	NSTryAuthWithServer( file.lastSelectedServer.index, password )

	ToggleConnectingHUD( true )

	while ( NSIsAuthenticatingWithServer() && !file.cancelConnection )
	{
		WaitFrame()
	}

	ToggleConnectingHUD( false )

	if ( file.cancelConnection )
	{
		file.cancelConnection = false
		// re-focus server list
		Hud_SetFocused( Hud_GetChild( file.menu, "BtnServer" + ( file.serverButtonFocusedID + 1 ) ) )
		return
	}

	file.cancelConnection = false

	if ( NSWasAuthSuccessful() )
	{
		bool modsChanged = false

		// disable all RequiredOnClient mods that are not required by the server and are currently enabled
		foreach ( string modName in NSGetModNames() )
		{
			if ( NSIsModRequiredOnClient( modName ) && NSIsModEnabled( modName ) )
			{
				// find the mod name in the list of server required mods
				bool found = false
				foreach ( RequiredModInfo mod in file.lastSelectedServer.requiredMods )
				{
					if (mod.name == modName)
					{
						found = true
						break
					}
				}
				// if we didnt find the mod name, disable the mod
				if (!found)
				{
					modsChanged = true
					NSSetModEnabled( modName, false )
				}
			}
		}

		// enable all RequiredOnClient mods that are required by the server and are currently disabled
		foreach ( RequiredModInfo mod in file.lastSelectedServer.requiredMods )
		{
			if ( NSIsModRequiredOnClient( mod.name ) && !NSIsModEnabled( mod.name ))
			{
				modsChanged = true
				NSSetModEnabled( mod.name, true )
			}
		}

		// only actually reload if we need to since the uiscript reset on reload lags hard
		if ( modsChanged )
			ReloadMods()

		NSConnectToAuthedServer()
	}
	else
	{
		string reason = NSGetAuthFailReason()

		DialogData dialogData
		dialogData.header = "#ERROR"
		dialogData.message = reason
		dialogData.image = $"ui/menu/common/dialog_error"

		#if PC_PROG
			AddDialogButton( dialogData, "#DISMISS" )

			AddDialogFooter( dialogData, "#A_BUTTON_SELECT" )
		#endif // PC_PROG
		AddDialogFooter( dialogData, "#B_BUTTON_DISMISS_RUI" )

		OpenDialog( dialogData )
	}
}

//////////////////////////////////////
// Shadow realm
//////////////////////////////////////
int function ServerSortLogic ( ServerInfo a, ServerInfo b )
{
	var aTemp
	var bTemp

	bool direction

	// We can hard code this cause adding entire columns isn't as easy
	switch ( filterDirection.sortingBy )
	{
		case sortingBy.DEFAULT:
			aTemp = a.playerCount
			bTemp = b.playerCount

			// `1000` is assumed to always be higher than `serverPlayersMax`
			if (aTemp + 1 < a.maxPlayerCount)
				aTemp = aTemp+2000
			if (bTemp + 1 < b.maxPlayerCount)
				bTemp = bTemp+2000
			if (aTemp + 1 == a.maxPlayerCount)
				aTemp = aTemp+1000
			if (bTemp + 1 == b.maxPlayerCount)
				bTemp = bTemp+1000

			direction = filterDirection.serverName
			break;
		case sortingBy.NAME:
			aTemp = a.name.tolower()
			bTemp = b.name.tolower()
			direction = filterDirection.serverName
			break;
		case sortingBy.PLAYERS:
			aTemp = a.playerCount
			bTemp = b.playerCount
			direction = filterDirection.serverPlayers
			break;
		case sortingBy.MAP:
			aTemp = Localize( a.map ).tolower()
			bTemp = Localize( b.map ).tolower()
			direction = filterDirection.serverMap
			break;
		case sortingBy.GAMEMODE:
			aTemp = Localize( a.playlist ).tolower()
			bTemp = Localize( b.playlist ).tolower()
			direction = filterDirection.serverGamemode
			break;
		case sortingBy.REGION:
			aTemp = a.region
			bTemp = b.region
			direction = filterDirection.serverRegion
			break;
		default:
			return 0
	}

	int invert = direction == true ? 1 : -1

	if ( aTemp > bTemp )
		return 1 * invert

	if ( aTemp < bTemp )
		return -1 * invert

	return 0
}

void function SortServerListByDefault_Activate ( var button )
{
	filterDirection.sortingBy = sortingBy.DEFAULT

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverName = !filterDirection.serverName

	UpdateShownPage()
}


void function SortServerListByName_Activate ( var button )
{
	filterDirection.sortingBy = sortingBy.NAME

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverName = !filterDirection.serverName

	UpdateShownPage()
}


void function SortServerListByPlayers_Activate( var button )
{
	filterDirection.sortingBy = sortingBy.PLAYERS

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverPlayers = !filterDirection.serverPlayers

	UpdateShownPage()
}

void function SortServerListByMap_Activate( var button )
{
	filterDirection.sortingBy = sortingBy.MAP

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverMap = !filterDirection.serverMap

	UpdateShownPage()
}

void function SortServerListByGamemode_Activate( var button )
{
	filterDirection.sortingBy = sortingBy.GAMEMODE

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverGamemode = !filterDirection.serverGamemode

	UpdateShownPage()
}

void function SortServerListByRegion_Activate( var button )
{
	filterDirection.sortingBy = sortingBy.REGION

	file.filteredServers.sort( ServerSortLogic )

	filterDirection.serverRegion = !filterDirection.serverRegion

	UpdateShownPage()
}

//////////////////////////////////////
// Callbacks
//////////////////////////////////////

void function AddConnectToServerCallback( void functionref( ServerInfo ) callback )
{
	if ( file.connectCallbacks.find( callback ) >= 0 )
		throw "ConnectToServerCallback has been registered twice. Duplicate callbacks are not allowed."
	file.connectCallbacks.append( callback )
}

void function RemoveConnectToServerCallback( void functionref( ServerInfo ) callback )
{
	file.connectCallbacks.fastremovebyvalue( callback )
}

void function TriggerConnectToServerCallbacks( ServerInfo ornull targetServer = null )
{
	ServerInfo server;
	if (targetServer == null)
	{
		targetServer = file.lastSelectedServer
	}

	foreach( callback in file.connectCallbacks )
	{
		callback( expect ServerInfo( targetServer ) )
	}
}