-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscoutingsdk.js
More file actions
6786 lines (6560 loc) · 319 KB
/
scoutingsdk.js
File metadata and controls
6786 lines (6560 loc) · 319 KB
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
const ScoutingAppSDK = function (element, config) {
let _this = this;
config = fixConfig(config);
element.innerHTML = ``;
const importantQuotes = [
"What is Red? How can you prove the Red you see is the Red others see? Its just labels",
"The Brain to notes synapse is much faster than limited app tracking.",
"Try doing that sheet over and over , not faster than paper, pen highlighters",
"Whatever… not trying to counter that as its non- stuff",
"The app is now on the back burner until they go though this entire season using our existing paper/excel /highlighter method.",
"Do you watch sports by reviewing stats? That is Fantasy football…fantasy.",
"Digital is 0 and 1, analog is infinite. Not that hard to understand…apps ARE digital. Human Brains are ANALOG",
"Most of the “app stuff” is driven by smartphones and an electronic generation",
"Look at Vegas , Vegas still wins despite card counters. Teams win for reasons other than fantastic scouting.",
"Most tracking systems are digital, we choose analog…so do Musicians both are valid",
"As for “scouting” :not found at all in last years Game and Season Manual",
"60-100 teams to track…not that hard some are good some are not.",
"I base most of our scouting off horse racing. Seems to work well.",
"Seems like scouting award is fluff. Same for strategy. Cream rises to the top",
"If students cant track 30-50 items without AI “help” there's a problem Houston. ",
"weak waffle language",
"One of the biggest issues with Apps…they are limited by design , the human brain is not limited by constraints.",
"QR codes have been around for years not really that innovative in fact originally used in car manufacturing and everyone has seen them",
"I know personally how hard it is for a team to win a Blue Banner",
"There is not a single student that I have come across that sees the game like I do.",
"These notes need to be passionate and not just entries, written by someone who gets the goals of scouting.",
"Did Apollo use computers primarily? How about Jet travel? Or even discovering other continents ?",
"Better than “fancy app” they worked so hard on you can place that in Chairmans or something"
];
const quotes = [
"Qualitative scouting is a completely valid way to track teams. The sample size is well within the scout teams ability to rank teams and find ways to use partners and defeat opponents.",
"Like any sport, you waste their time and frustrate them into fouls , while ahead then if they break you and go back to scoring 1 for 1 … you win. ",
"― Sun Tzu, The Art of War",
"Confirmation bias , the tendency to process information by looking for, or interpreting, information that is consistent with one's existing beliefs.",
"Scouting is about overall performance, are they a good partner ? If foe how to defeat?",
"A “scouting form” is actually a terrible idea.",
"We do 100% Qualitative scouting (Excel scheds, paper, pen, highlighter and shorthand notes)",
"Correct name , never not correct",
"the whole thinking was app or bust . Until we spoke.",
"Yes leaving that debate to rest. I like Citrus Dad and respect his views, I have my own.",
"Know your own limitations and find solutions. Its simple. Observe. There is not an app for that IMO as an app has you looking down.",
"Blue alliance has plenty of data from FMS…watching closely tells you who is good. Pen , highlighter excel with watch lists.",
"Teams will lie, best to use you own eyes and only track what you need to form an event winning alliance",
"If the team makes eliminations/worlds before , they are very likely to win in the future. If they never make eliminations, then they are unlikely to do so in the future.",
"So everyone is a winner won? First robotics competition",
"I am not going to continue to express my opinions or scouting practices in this thread as they find it “off topic” as it wasn't deemed “useful for future readers” hence the OP requested “clean up”.",
'And attacked by @ Stryker (with 18 loves) "individual being notorious for sharing eccentric opinions without appropriate defenses for them."',
"Bye this thread enjoy your own opinions then, have at it",
"I'll take a brain over and app…especially in a limited field size and low sample size",
"I don't think this is at all different than sports or horse racing, same principles apply",
"What does that mean exactly, does a number tell you “pick me”? There are many ways to do scouting, that's for certain",
"We track all sorts of weird stuff that changes year to year. Stuff we believe in.",
"Scouts are experienced talent evaluators who travel extensively for the purposes of watching athletes play their chosen sports and determining whether their set of skills and talents represent what is needed by the scout's organization.",
"In the end if you do scouting well , you know your team well. Then its a matter of building the strongest alliance to have a good chance against all comers",
"Not true if you LEAVE… seriously stop trying to win this argument",
"Have you ever gone to a horse race with a new person that picks winners by “Cutesy Name”? It happens they pick a cute name and they win",
"I suspect most wins at regional and championship are simple pair ups…not driven by any scouting app.",
"Observation and notes can trump fancy new “just in” technology rich scouting app",
"Amazing the worlds best inventions were accomplished without a single computer.",
"Not that hard to “track” 30-50 teams in most competitions.",
"Note 3: Not following the crowd, can be beneficial (see 2009 financial “crisis”)",
"This scouting award will certainly be dominated by a subset of more boisterous teams",
"Back to Horseracing, if it was easy to pick a winner don't you think with all the money involved , someone would create a program to pick a winner every time? Hasn't happened.",
"Sure 1678 has a great record and would not have been “as great” without scouting doing its job.",
"No amount of notes will convey what a simple conversation can convey as humans take visual cues from each other.",
"Scouting involves luck. look at handicappers or stock brokers… its all luck finding the trend at the right time. There is no magic sauce. ",
"Golden Worm Blasters",
"I decided to comment based on my experience with students. No harm no foul. Sorry if a resolution was reached 3 mo ago",
"What scouting brings is Intelligence… this bodes well in team interactions and gives you the intelligence high ground in competition or picking.",
"The class handicapper judges the merits of a horse not by the time of his recent races, but by the type of company in which he has been competing",
"Dealing with say 50 teams and say 10 matches to rely on data pointing the way is problematic",
"I still dismiss your quaint notion Blue Banners don't matter!",
"I will refine, ask away its about assembling the best pick list, right? I have much to offer there.",
"The single most important stat in horse racing is “class” don't under estimate that quality. I've learned from experience there.",
"Don't use apps",
"Look at music…CD/streaming are cheap and acceptabe, yet LP albums are purer.",
"We have [a blue banner]…strive for more every season. Not for everyone and thats fine",
"NOT season",
"This thread is a no win scenario and should end for the good of the game. Mods shut it down.",
"I me thinks get a lot of silent likes and that is a-ok there are still critical thinkers here.",
"winner winner chicken dinner",
"Scouting apps are good programming exercise, usefulness not determined. It’s like weigh watching apps, stock apps, horoscope apps. It makes you feels good and it’s fun to program",
"Tracking the right stuff in a game is important, does the scouting app do that? Do you trust the data? What insights are gained?",
"Always open your mind to what is possible.",
"But does an App track tendency? Does an App track where a robot likes to play? Does an app guarantee good data or bored scouts? Great drivers, Repair tendencies?",
"Its not about data , its the right data",
"Human processing blows away a computer except in certain tasks",
"Pen + Paper + Highlighter + Excel, much more configurable. It always perplexes me why tracikng 40-60 robots requires an app? Except to give programmers something to do?"
];
const MAX_QR_LENGTH = 128;
function checkNull(object1, object2) {
return object1 !== null && object1 !== undefined ? object1 : object2;
}
_this.escape = (string) => {
const escapedChars = [
{ character: "&", replacement: "&" },
{ character: "<", replacement: "<" },
{ character: ">", replacement: ">" },
{ character: '"', replacement: """ },
{ character: "'", replacement: "'" }
];
if (string === null || typeof string !== "string") {
return string;
}
let result = string;
for (let i = 0; i < escapedChars.length; i++) {
result = result.replace(
new RegExp(escapedChars[i].character, "g"),
escapedChars[i].replacement
);
}
return result;
};
_this.normalize = (string) => {
const validChars = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
".",
"!",
"?",
"(",
")"
];
let normalized = [];
for (let i = 0; i < string.length; i++) {
if (validChars.includes(string[i].toLowerCase())) {
normalized.push(string[i]);
} else {
normalized.push(" ");
}
}
return normalized.join("");
};
_this.formatData = (eventCode, matchNumber, teamNumber, data) => {
data = { ...data };
data.data = { ...data.data };
data.abilities = { ...data.abilities };
data.counters = { ...data.counters };
data.timers = { ...data.timers };
data.ratings = { ...data.ratings };
let formatted = {
data: [],
abilities: [],
counters: [],
timers: [],
ratings: [],
comments: data.data.comments || "",
timestamp: new Date().getTime()
};
if (data.data.comments != null) {
delete data.data.comments;
}
let dataKeys = Object.keys(data.data);
let abilityKeys = Object.keys(data.abilities);
let counterKeys = Object.keys(data.counters);
let timerKeys = Object.keys(data.timers);
let ratingKeys = Object.keys(data.ratings);
for (let i = 0; i < dataKeys.length; i++) {
formatted.data[i] = {
category: dataKeys[i],
data: data.data[dataKeys[i]]
};
}
for (let i = 0; i < abilityKeys.length; i++) {
formatted.abilities[i] = {
category: abilityKeys[i],
ability: data.abilities[abilityKeys[i]]
};
}
for (let i = 0; i < counterKeys.length; i++) {
formatted.counters[i] = {
category: counterKeys[i],
counter: data.counters[counterKeys[i]]
};
}
for (let i = 0; i < timerKeys.length; i++) {
formatted.timers[i] = {
category: timerKeys[i],
timer: data.timers[timerKeys[i]]
};
}
for (let i = 0; i < ratingKeys.length; i++) {
formatted.ratings[i] = {
category: ratingKeys[i],
rating: data.ratings[ratingKeys[i]]
};
}
console.log(formatted);
return formatted;
};
_this.stringifyFormatted = (
eventCode,
matchNumber,
teamNumber,
color,
formatted
) => {
let stringified = JSON.stringify([
config.account.team,
formatted.username || config.account.username,
eventCode,
matchNumber,
teamNumber,
color,
formatted.data.map((dataObj) => [
"category",
dataObj.category,
"data",
dataObj.data
]),
formatted.abilities.map((abilityObj) => [
"category",
abilityObj.category,
"ability",
abilityObj.ability
]),
formatted.counters.map((counterObj) => [
"category",
counterObj.category,
"counter",
counterObj.counter
]),
formatted.timers.map((timerObj) => [
"category",
timerObj.category,
"timer",
timerObj.timer
]),
formatted.ratings.map((ratingObj) => [
"category",
ratingObj.category,
"rating",
ratingObj.rating
]),
formatted.comments
]);
return stringified;
};
_this.updateIncentives = (incentives) => {
function periodic(func, times, ms, timesDropoff = -1) {
if (timesDropoff == -1) {
timesDropoff = times;
}
if (times > 0) {
func();
setTimeout(() => {
periodic(func, times - 1, ms, timesDropoff - 0.995);
}, Math.ceil(ms / timesDropoff));
}
}
let nutsElement = document.querySelector(
".header-incentives .nuts > p"
);
let nutsElementShop = document.querySelector(
".shop-balance .nuts span"
);
let boltsElement = document.querySelector(
".header-incentives .bolts > p"
);
let boltsElementShop = document.querySelector(
".shop-balance .bolts span"
);
let levelsElement = document.querySelector(".header-incentives .xp p");
let progressElement = document.querySelector(
".header-incentives .xp .xp-filled"
);
let differenceNuts =
incentives.totals.nuts - parseInt(nutsElement.innerHTML);
let differenceBolts =
incentives.totals.bolts - parseInt(boltsElement.innerHTML);
let differenceNutsShop =
incentives.totals.nuts - parseInt(nutsElementShop.innerHTML);
let differenceBoltsShop =
incentives.totals.bolts - parseInt(nutsElementShop.innerHTML);
let differenceLevels =
incentives.totals.level - parseInt(levelsElement.innerHTML);
let differenceProgress =
100 * differenceLevels +
(incentives.totals.progress * 100 -
parseInt(progressElement.style.width.replace("%", "")));
periodic(
() => {
nutsElement.innerHTML =
parseInt(nutsElement.innerHTML) +
Math.abs(differenceNuts) / differenceNuts;
nutsElementShop.innerHTML =
parseInt(nutsElementShop.innerHTML) +
Math.abs(differenceNutsShop) / differenceNutsShop;
},
Math.abs(differenceNuts),
500
);
periodic(
() => {
boltsElement.innerHTML =
parseInt(boltsElement.innerHTML) +
Math.abs(differenceBolts) / differenceBolts;
boltsElementShop.innerHTML =
parseInt(boltsElementShop.innerHTML) +
Math.abs(differenceBoltsShop) / differenceBoltsShop;
},
Math.abs(differenceBolts),
500
);
if (differenceProgress > 0) {
periodic(
() => {
progressElement.style.width = `${
parseInt(progressElement.style.width.replace("%", "")) +
1
}%`;
if (
parseInt(
progressElement.style.width.replace("%", "")
) >= 100
) {
progressElement.style.width = "0%";
levelsElement.innerHTML =
parseInt(levelsElement.innerHTML) + 1;
}
},
differenceProgress,
500
);
}
};
let timers = {};
window.t = timers;
let checkboxes = {};
window.c = checkboxes;
let data = {
data: {},
abilities: {},
counters: {},
timers: {},
ratings: {}
};
_this.revealTimers = () => {
console.log(timers);
};
_this.revealCheckboxes = () => {
console.log(checkboxes);
};
_this.showHomePage = (
_eventCode = "",
_matchNumber = "",
_teamNumber = ""
) => {
return new Promise(async (resolve, reject) => {
await _this.setMatchNav(0, undefined, undefined, undefined);
data = {
data: {},
abilities: {},
counters: {},
timers: {},
ratings: {}
};
timers = {};
checkboxes = {};
if (
_eventCode != "" &&
_this.getEventCode() != null &&
_this.getEventCode() != ""
) {
_this.setEventCode(_eventCode);
}
let latestMatch = "";
if (config.latest.autofill) {
let latestMatchData = await _this.getLatestMatch(
_this.getEventCode()
);
if (latestMatchData.success) {
latestMatch = latestMatchData.body.latest + 1;
}
}
let year =
config.year || new Date().toLocaleDateString().split("/")[2];
let events = await _this.getEvents(year);
element.innerHTML = `
<div class="home-window">
<div class="title-block">
<h1>Begin scouting</h1>
</div>
<div class="group">
<input class="match-number" id="match-number" autocomplete="off" name="Match" type="number" min="0" required="required" value="${_this.escape(
_matchNumber || latestMatch
)}"/></span><span class="bar"></span>
<label for="match-number">Match Number</label>
</div>
<select class="event-code">
<option value=""${
(_eventCode || _this.getEventCode()) == null ||
(_eventCode || _this.getEventCode()) == ""
? " selected"
: ""
}>Select an event...</option>
${events.map(
(event) =>
`<option value="${event.key}"${
(_eventCode || _this.getEventCode()) ==
event.key
? " selected"
: ""
}>${event.name}</option>`
)}
</select>
<select class="team">
<option value="">Select a team...</option>
</select>
<p class="red warning"></p>
<button class="start">Start</button>
<p class="boltman-quote">${_this.escape(
_this.getQuote()
)}</p>
<p class="footer-text">Made with < > by <a href="https://robotics.harker.org/" target="_blank">Harker Robotics</a></p>
</div>
`;
let eventCode = element.querySelector(
".home-window > select.event-code"
).value;
if (eventCode != null && eventCode != "") {
_this.setMatches(eventCode);
}
element.querySelector(".home-window > button.start").onclick =
async () => {
let eventCode = element.querySelector(
".home-window > select.event-code"
).value;
let matchNumber = parseInt(
element.querySelector(".home-window input.match-number")
.value
);
let teamNumber = element.querySelector(
".home-window > select.team"
).value;
if (
eventCode != null &&
eventCode != "" &&
matchNumber != null &&
matchNumber != "" &&
teamNumber != null &&
teamNumber != ""
) {
await _this.showMatchPage(
0,
eventCode,
matchNumber,
teamNumber
);
}
};
element.querySelector(".home-window > select.event-code").onchange =
async () => {
element.querySelector(".home-window > .warning").innerHTML =
"";
let eventCode = element.querySelector(
".home-window > select.event-code"
).value;
_this.setEventCode(eventCode);
_this.setMatches(eventCode);
let latestMatch = "";
if (config.latest.autofill) {
let latestMatchData = await _this.getLatestMatch(
_this.getEventCode()
);
if (latestMatchData.success) {
latestMatch = latestMatchData.body.latest + 1;
}
}
element.querySelector(".match-number").value = latestMatch;
updateTeamsList();
};
let updateTeamsList = async () => {
element.querySelector(
".home-window > select.team"
).innerHTML = `<option value="">Select a team...</option>`;
let eventCode = element.querySelector(
".home-window > select.event-code"
).value;
let matchNumber = parseInt(
element.querySelector(".home-window input.match-number")
.value
);
if (
eventCode != "" &&
matchNumber != "" &&
!isNaN(parseInt(matchNumber))
) {
let match = await _this.getMatch(eventCode, matchNumber);
let redTeams = match.alliances.red.team_keys;
let blueTeams = match.alliances.blue.team_keys;
let teams = `<option value="">Select a team...</option>`;
for (let i = 0; i < redTeams.length; i++) {
let teamNumber = redTeams[i].replace("frc", "");
teams += `
<option value="${_this.escape(teamNumber)}"${
teamNumber == _teamNumber ? " selected" : ""
}>
${_this.escape(teamNumber)} (Red ${i + 1})
</option>`;
}
for (let i = 0; i < blueTeams.length; i++) {
let teamNumber = blueTeams[i].replace("frc", "");
teams += `
<option value="${_this.escape(teamNumber)}"${
teamNumber == _teamNumber ? " selected" : ""
}>
${_this.escape(teamNumber)} (Blue ${i + 1})
</option>`;
}
element.querySelector(
".home-window > select.team"
).innerHTML = teams;
if (
!element
.querySelector(".home-window > select.event-code")
.value.endsWith("-prac") &&
["1r", "2r", "3r", "1b", "2b", "3b"].includes(
element.querySelector(".home-window > select.team")
.value
)
) {
element.querySelector(
".home-window > .warning"
).innerHTML =
"WARNING: It appears that qualification matches are not currently running for this event. If you are scouting practice matches, please use the PRACTICE MATCHES event. If qualification matches are indeed running, please connect to the internet briefly in order to download the list of teams.";
} else {
element.querySelector(
".home-window > .warning"
).innerHTML = "";
}
}
};
element.querySelector(".home-window > select.team").onchange =
function () {
let team = element.querySelector(
".home-window > select.team"
).value;
if (
["1r", "2r", "3r", "1b", "2b", "3b"].includes(team) ||
element
.querySelector(
`.home-window > select.team > option[value="${team}"]`
)
.innerHTML.includes("Override")
) {
let newTeam = prompt(
`Please enter a team number or leave this field blank to use ${team} as the team number`
);
newTeam = newTeam.replaceAll(" ", "").toUpperCase();
if (newTeam != "" && !isNaN(parseInt(newTeam))) {
document.querySelector(
`.home-window > select.team > option[value="${team}"]`
).innerHTML = `${newTeam} (Override)`;
document.querySelector(
`.home-window > select.team > option[value="${team}"]`
).value = newTeam;
team = newTeam;
}
}
if (
!element
.querySelector(".home-window > select.event-code")
.value.endsWith("-prac") &&
["1r", "2r", "3r", "1b", "2b", "3b"].includes(team)
) {
element.querySelector(
".home-window > .warning"
).innerHTML =
"WARNING: It appears that qualification matches are not currently running for this event. If you are scouting practice matches, please use the PRACTICE MATCHES event. If qualification matches are indeed running, please connect to the internet briefly in order to download the list of teams.";
} else {
element.querySelector(
".home-window > .warning"
).innerHTML = "";
}
};
element.querySelector(".home-window input.match-number").onblur =
updateTeamsList;
updateTeamsList();
resolve();
});
};
_this.showMatchPage = (index, eventCode, matchNumber, teamNumber) => {
return new Promise(async (resolve, reject) => {
_this.currentPage = index;
if (index < -1) {
_this.clearPendingFunctions();
pendingFunctions.push(async () => {
await this.setMatchNav(
0,
eventCode,
matchNumber,
teamNumber
);
});
await _this.showHomePage();
} else if (index < 0) {
_this.clearPendingFunctions();
pendingFunctions.push(async () => {
await this.setMatchNav(
0,
eventCode,
matchNumber,
teamNumber
);
});
await _this.showHomePage(eventCode, matchNumber, teamNumber);
} else {
pendingFunctions.push(async () => {
await this.setMatchNav(
index == 0 ? 1 : 2,
eventCode,
matchNumber,
teamNumber
);
});
element.innerHTML = `
<div class="match-window">
${await _this.compileComponent(
eventCode,
matchNumber,
teamNumber,
config.pages[index]
)}
</div>
<div class="overlay"></div>
<div class="location-popup"></div>
`;
await _this.runPendingFunctions();
}
resolve();
});
};
_this.setMatchNav = (toggle, eventCode, matchNumber, teamNumber) => {
return new Promise(async (resolve, reject) => {
const nav = document.querySelector("header");
const regEls = Array.from(nav.querySelectorAll(".reg-nav"));
const matchEls = Array.from(nav.querySelectorAll(".match-nav"));
if (regEls) {
let cl = toggle != 0 ? "add" : "remove";
regEls.forEach((el) => {
el.classList[cl]("none");
});
}
if (matchEls) {
let cl = toggle != 0 ? "remove" : "add";
matchEls.forEach((el) => {
el.classList[cl]("none");
});
}
const submit = document.getElementById("submit-button");
const back = document.getElementById("back-button");
if (!submit || !back) {
console.log("nav buttons not defined!");
return;
}
if (toggle == 1) {
submit.classList.remove("none");
back.classList.add("none");
submit.onclick = async () => {
await _this.showMatchPage(
parseInt(_this.currentPage) + 1,
eventCode,
matchNumber,
teamNumber
);
};
if (document.getElementById("scout-number"))
document.getElementById("scout-number").innerText =
teamNumber;
} else if (toggle == 2) {
submit.classList.add("none");
back.classList.remove("none");
back.onclick = async () => {
await _this.showMatchPage(
Math.min(parseInt(_this.currentPage) - 1, 1),
eventCode,
matchNumber,
teamNumber
);
};
if (document.getElementById("scout-number"))
document.getElementById("scout-number").innerText =
teamNumber;
}
resolve();
});
};
function getQRScannerSize() {
return Math.floor(
Math.min(window.innerWidth - 200, window.innerHeight - 200)
);
}
_this.uploadData = async (data) => {
let formatted = _this.formatData(data.ec, data.mn, data.tn, {
data: data.d,
abilities: data.a,
counters: data.c,
timers: data.t,
ratings: data.r
});
if (data.at == config.account.team) {
formatted.username = data.au;
} else {
formatted.username = `team${data.at}-${data.au}`;
}
try {
console.log("Preparing...");
console.log("Uploading...");
let upload = await (
await fetch(
`/api/v1/scouting/entry/add/${encodeURIComponent(
data.ec
)}/${encodeURIComponent(data.mn)}/${encodeURIComponent(
data.tn
)}/${encodeURIComponent(data.tc)}`,
{
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
body: JSON.stringify(formatted)
}
)
).json();
if (upload.success) {
console.log("Verifying...");
let stringified = _this.stringifyFormatted(
data.ec,
data.mn,
data.tn,
data.tc,
formatted
);
let hash = _this.hash(stringified);
let verify = await (
await fetch(
`/api/v1/scouting/entry/verify/${encodeURIComponent(
hash
)}`
)
).json();
if (verify.success && verify.body.verified) {
let incentives = [];
if (upload.body.xp - upload.body.accuracyBoosters.xp > 0) {
incentives.push(
`+${
upload.body.xp - upload.body.accuracyBoosters.xp
} XP`
);
}
if (
upload.body.nuts - upload.body.accuracyBoosters.nuts >
0
) {
incentives.push(
`+${
upload.body.nuts -
upload.body.accuracyBoosters.nuts
} Nuts`
);
}
if (
upload.body.bolts - upload.body.accuracyBoosters.bolts >
0
) {
incentives.push(
`+${
upload.body.bolts -
upload.body.accuracyBoosters.bolts
} Bolts`
);
}
let offset = 0;
if (incentives.length > 0) {
offset = 100;
setTimeout(() => {
console.log(`${incentives.join(", ")}`);
}, offset);
}
if (upload.body.accuracyBoosters.xp > 0) {
offset += 100;
setTimeout(() => {
console.log(
`+${upload.body.accuracyBoosters.xp} XP (Accuracy Boost)`
);
}, offset);
}
if (upload.body.accuracyBoosters.nuts > 0) {
offset += 100;
setTimeout(() => {
console.log(
`+${upload.body.accuracyBoosters.nuts} Nuts (Accuracy Boost)`
);
}, offset);
}
if (upload.body.accuracyBoosters.bolts > 0) {
offset += 100;
setTimeout(() => {
console.log(
`+${upload.body.accuracyBoosters.bolts} Bolts (Accuracy Boost)`
);
}, offset);
}
setTimeout(() => {
console.log("Success!");
_this.updateIncentives(upload.body);
}, offset);
} else {
console.log(stringified);
console.log(
`Upload Failed!\n${
verify.error ||
"Unable to verify upload completion."
}`
);
}
} else {
console.log(
`Upload Failed!\n${upload.error || "Unknown error."}`
);
}
} catch (err) {
console.error(err);
console.log(`Upload Failed!\nCould not connect to the server.`);
}
};
_this.showScannerPage = (view = 0) => {
return new Promise(async (resolve, reject) => {
await _this.setMatchNav(0, undefined, undefined, undefined);
element.innerHTML = `
<div class="scanner-window">
<div class="scanner-view" style="display: ${
view == 0 ? "flex" : "none"
};">
<button class="use-text-input">Use Text Input</button>
<button class="switch-camera">Switch Camera</button>
<div class="scanned-label"><h4>QR Codes Scanned: </h4><p></p></div>
<div class="reader" id="reader"></div>
<div class="upload"></div>
<button style="display: none;" class="scan-again">Scan Again</button>
</div>
<div class="upload-view" style="display: ${
view == 1 ? "flex" : "none"
};">
<button class="use-scanner">Use Scanner</button>
<textarea class="upload-box"></textarea>
<button class="upload-data">Upload</button>
<div class="upload"></div>
<button style="display: none;" class="upload-again">Upload Again</button>
</div>
</div>
`;
let reader = {
stop: () => {}
};
if (view == 0) {
reader = new Html5Qrcode("reader");
}
element.querySelector("button.scan-again").onclick = async () => {
try {
await reader.stop();
} catch (err) {}
await _this.showScannerPage(0);
};
element.querySelector("button.upload-again").onclick = async () => {
try {
await reader.stop();
} catch (err) {}
await _this.showScannerPage(1);
};
element.querySelector("button.use-text-input").onclick =
async () => {
try {
await reader.stop();
} catch (err) {}
await _this.showScannerPage(1);
};
element.querySelector("button.use-scanner").onclick = async () => {
try {
await reader.stop();
} catch (err) {}
await _this.showScannerPage(0);
};
let devices = [];
let codes = [];
let deviceIndex = 0;
async function scanResult(decodedText, decodedResult) {
try {
let data = JSON.parse(decodedText);
codes[data[0]] = data[2];
element.querySelector(".scanner-view p").innerHTML = `${
codes.filter((code) => code != null).length
}/${data[1]}`;
if (
codes.filter((code) => code != null).length == data[1]
) {
console.log(codes.join(""));
let data = JSON.parse(codes.join(""));
let formatted = _this.formatData(
data.ec,
data.mn,
data.tn,
{
data: data.d,
abilities: data.a,
counters: data.c,
timers: data.t,
ratings: data.r
}
);
if (data.at == config.account.team) {
formatted.username = data.au;
} else {
formatted.username = `team${data.at}-${data.au}`;
}
element.querySelector(
".scanner-view > .scanned-label"
).innerHTML = " ";
await reader.stop();
element.querySelector(
".scanner-view > button.switch-camera"
).style.display = "none";
try {