aboutsummaryrefslogtreecommitdiff
path: root/src/database.ts
blob: fd3f52b78b8db6bdaef471e3682bd9e84e20e1b0 (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
/**
 * Store data about members for leaderboards
*/

import { categorizeStat, getStatUnit } from './cleaners/skyblock/stats.js'
import { CleanFullProfile } from './cleaners/skyblock/profile.js'
import { SLAYER_TIERS } from './cleaners/skyblock/slayers.js'
import { Binary, Collection, Db, MongoClient, WithId } from 'mongodb'
import { CleanMember } from './cleaners/skyblock/member.js'
import * as cached from './hypixelCached.js'
import * as constants from './constants.js'
import { isUuid, letterFromColorCode, minecraftColorCodes, shuffle, sleep } from './util.js'
import * as discord from './discord.js'
import NodeCache from 'node-cache'
import { v4 as uuid4 } from 'uuid'
import { debug } from './index.js'
import Queue from 'queue-promise'
import { RANK_COLORS } from './cleaners/rank.js'
import { cleanItemId } from './cleaners/skyblock/itemId.js'
import { periodicallyFetchRecentlyEndedAuctions } from './hypixel.js'

// don't update the user for 3 minutes
const recentlyUpdated = new NodeCache({
	stdTTL: 60 * 3,
	checkperiod: 60,
	useClones: false,
})

// don't add stuff to the queue within the same 5 minutes
const recentlyQueued = new NodeCache({
	stdTTL: 60 * 5,
	checkperiod: 60,
	useClones: false,
})

interface DatabaseMemberLeaderboardItem {
	uuid: string
	profile: string
	/** The color code of this player's rank */
	color: string
	username: string
	stats: Record<string, number>
	lastUpdated: Date
}
interface DatabaseProfileLeaderboardItem {
	uuid: string
	/** The color codes of the players ranks */
	colors: string[]
	/** An array of uuids for each player in the profile */
	players: string[]
	usernames: string[]
	stats: Record<string, number>
	lastUpdated: Date
}


interface MemberRawLeaderboardItem {
	uuid: string
	profile: string
	color: string
	username: string
	value: number
}
interface ProfileRawLeaderboardItem {
	uuid: string
	/** An array of uuids for each player in the profile */
	players: string[]
	colors: string[]
	usernames: string[]
	value: number
}

interface MemberLeaderboardItem {
	player: LeaderboardBasicPlayer
	profileUuid: string
	value: number
}
interface ProfileLeaderboardItem {
	players: LeaderboardBasicPlayer[]
	profileUuid: string
	value: number
}

export const cachedRawLeaderboards: Map<string, (MemberRawLeaderboardItem | ProfileRawLeaderboardItem)[]> = new Map()

const LEADERBOARD_MAX = 100
const reversedLeaderboards = [
	'first_join', 'last_save',
	'_best_time', '_best_time_2',
	'fastest_coop_join', 'fastest_target_practice'
]

let client: MongoClient
let database: Db

interface SessionSchema {
	_id?: string
	refresh_token: string
	discord_user: {
		id: string
		name: string
	}
	lastUpdated: Date
}

export interface AccountCustomization {
	backgroundUrl?: string
	pack?: string
	blurBackground?: boolean
	emoji?: string
}

export interface AccountSchema {
	_id?: string
	discordId: string
	minecraftUuid?: string
	customization?: AccountCustomization
}

export interface SimpleAuctionSchemaBson {
	/** The UUID of the auction so we can look it up later. */
	id: Binary
	coins: number
	/**
	 * The timestamp as **seconds** since epoch. It's in seconds instead of ms
	 * since we don't need to be super exact and so it's shorter.
	 */
	ts: number
	/** Whether the auction was successfully bought or simply expired. */
	s: boolean
	bin: boolean
}
export interface SimpleAuctionSchema {
	/** The UUID of the auction so we can look it up later. */
	id: string
	coins: number
	/**
	 * The timestamp as **seconds** since epoch. It's in seconds instead of ms
	 * since we don't need to be super exact and so it's shorter.
	 */
	ts: number
	/** Whether the auction was successfully bought or simply expired. */
	s: boolean
	bin: boolean
}
export interface ItemAuctionsSchema {
	/** The id of the item */
	id: string
	sbId: string
	auctions: SimpleAuctionSchema[]
}
export interface ItemAuctionsSchemaBson {
	/** The id of the item */
	_id: string
	sbId: string
	auctions: SimpleAuctionSchemaBson[]
	/** This is here so it can be indexed by Mongo, it can easily be figured out by getting the first item in auctions */
	oldestDate: number
}

let memberLeaderboardsCollection: Collection<DatabaseMemberLeaderboardItem>
let profileLeaderboardsCollection: Collection<DatabaseProfileLeaderboardItem>
let sessionsCollection: Collection<SessionSchema>
let accountsCollection: Collection<AccountSchema>
let itemAuctionsCollection: Collection<ItemAuctionsSchemaBson>


const leaderboardInfos: { [leaderboardName: string]: string } = {
	highest_crit_damage: 'This leaderboard is capped at the integer limit. Look at the <a href="/leaderboard/highest_critical_damage">highest critical damage leaderboard</a> instead.',
	highest_critical_damage: 'uhhhhh yeah idk either',
	leaderboards_count: 'This leaderboard counts how many leaderboards a player is in the top 100 spot for.',
	top_1_leaderboards_count: 'This leaderboard counts how many leaderboards a player is in the #1 spot for.',
}


async function connect(): Promise<void> {
	if (!process.env.db_uri)
		return console.warn('Warning: db_uri was not found in .env. Features that utilize the database such as leaderboards won\'t work.')
	if (!process.env.db_name)
		return console.warn('Warning: db_name was not found in .env. Features that utilize the database such as leaderboards won\'t work.')
	client = await MongoClient.connect(process.env.db_uri)
	database = client.db(process.env.db_name)
	memberLeaderboardsCollection = database.collection('member-leaderboards')
	profileLeaderboardsCollection = database.collection('profile-leaderboards')
	sessionsCollection = database.collection('sessions')
	accountsCollection = database.collection('accounts')
	itemAuctionsCollection = database.collection('item-auctions')

	periodicallyFetchRecentlyEndedAuctions()

	console.log('Connected to database :)')
}

interface StringNumber {
	[name: string]: number
}

function createUuid(uuid: string): Binary {
	return new Binary(Buffer.from((uuid).replace(/-/g, ''), 'hex'), Binary.SUBTYPE_UUID)
}

function getMemberCollectionAttributes(member: CleanMember): StringNumber {
	const collectionAttributes = {}
	for (const collection of member.collections) {
		const collectionLeaderboardName = `collection_${collection.name}`
		collectionAttributes[collectionLeaderboardName] = collection.amount
	}
	return collectionAttributes
}

function getMemberSkillAttributes(member: CleanMember): StringNumber {
	if (!member.skills.apiEnabled) return {}
	const skillAttributes = {}
	for (const collection of member.skills.list) {
		const skillLeaderboardName = `skill_${collection.id}`
		skillAttributes[skillLeaderboardName] = collection.xp
	}
	return skillAttributes
}

function getMemberSlayerAttributes(member: CleanMember): StringNumber {
	const slayerAttributes: StringNumber = {
		slayer_total_xp: member.slayers.xp,
		slayer_total_kills: member.slayers.kills,
	}

	for (const slayer of member.slayers.bosses) {
		slayerAttributes[`slayer_${slayer.rawName}_total_xp`] = slayer.xp
		slayerAttributes[`slayer_${slayer.rawName}_total_kills`] = slayer.kills
		for (const tier of slayer.tiers) {
			slayerAttributes[`slayer_${slayer.rawName}_${tier.tier}_kills`] = tier.kills
		}
	}

	return slayerAttributes
}

function getMemberHarpAttributes(member: CleanMember): StringNumber {
	const harpAttributes: StringNumber = {}

	for (const song of member.harp.songs) {
		harpAttributes[`harp_${song.id}_completions`] = song.completions
		harpAttributes[`harp_${song.id}_perfect_completions`] = song.perfectCompletions
	}

	return harpAttributes
}

function getFarmingContestAttributes(member: CleanMember): StringNumber {
	const farmingContestAttributes: StringNumber = {}

	let participated = 0
	let top1 = 0

	let participatedRecord: StringNumber = {}
	let top1Record: StringNumber = {}
	let highestScoreRecord: StringNumber = {}

	for (const contest of member.farmingContests.list) {
		participated++
		for (const cropContest of contest.crops) {
			if (participatedRecord[cropContest.item] === undefined)
				participatedRecord[cropContest.item] = 0
			participatedRecord[cropContest.item]++

			if (highestScoreRecord[cropContest.item] === undefined || highestScoreRecord[cropContest.item] < cropContest.amount)
				highestScoreRecord[cropContest.item] = cropContest.amount

			if (cropContest.position === 1) {
				top1++
				if (top1Record[cropContest.item] === undefined)
					top1Record[cropContest.item] = 0
				top1Record[cropContest.item]++
			}
		}
	}
	farmingContestAttributes['farming_contests_participated'] = participated
	farmingContestAttributes['farming_contests_top_1'] = top1

	for (const [cropName, value] of Object.entries(participatedRecord))
		farmingContestAttributes[`farming_contests_participated_${cropName}`] = value
	for (const [cropName, value] of Object.entries(top1Record))
		farmingContestAttributes[`farming_contests_top_1_${cropName}`] = value
	for (const [cropName, value] of Object.entries(highestScoreRecord))
		farmingContestAttributes[`farming_contests_highest_score_${cropName}`] = value

	return farmingContestAttributes
}

function getMemberLeaderboardAttributes(member: CleanMember): StringNumber {
	// if you want to add a new leaderboard for member attributes, add it here (and getAllLeaderboardAttributes)
	const data: StringNumber = {
		// we use the raw stat names rather than the clean stats in case hypixel adds a new stat and it takes a while for us to clean it
		...member.rawHypixelStats,

		// collection leaderboards
		...getMemberCollectionAttributes(member),

		// skill leaderboards
		...getMemberSkillAttributes(member),

		// slayer leaderboards
		...getMemberSlayerAttributes(member),

		// harp leaderboards
		...getMemberHarpAttributes(member),

		// farming contest leaderboards
		...getFarmingContestAttributes(member),

		fairy_souls: member.fairySouls.total,
		purse: member.purse,
		visited_zones: member.zones.filter(z => z.visited).length,
	}

	if (member.firstJoin)
		data.first_join = member.firstJoin
	if (member.lastSave)
		data.last_save = member.lastSave

	if (member.coopInvitation && member.coopInvitation.acceptedTimestamp && member.coopInvitation?.invitedBy?.uuid !== member.uuid) {
		data.fastest_coop_join = member.coopInvitation.acceptedTimestamp - member.coopInvitation.invitedTimestamp
		data.slowest_coop_join = member.coopInvitation.acceptedTimestamp - member.coopInvitation.invitedTimestamp
	}

	const fastestTargetPractice = member.stats.find(s => s.rawName === 'fastest_target_practice')?.value
	if (fastestTargetPractice !== undefined)
		data.fastest_target_practice = fastestTargetPractice

	return data
}

function getProfileLeaderboardAttributes(profile: CleanFullProfile): StringNumber {
	// if you want to add a new leaderboard for member attributes, add it here (and getAllLeaderboardAttributes)
	return {
		unique_minions: profile.minionCount
	}
}


export async function fetchAllLeaderboardsCategorized(): Promise<{ [category: string]: string[] }> {
	const memberLeaderboardAttributes: string[] = await fetchAllMemberLeaderboardAttributes()
	const profileLeaderboardAttributes: string[] = await fetchAllProfileLeaderboardAttributes()

	const categorizedLeaderboards: { [category: string]: string[] } = {}
	for (const leaderboard of [...memberLeaderboardAttributes, ...profileLeaderboardAttributes]) {
		const { category } = categorizeStat(leaderboard)
		if (category) {
			if (!categorizedLeaderboards[category])
				categorizedLeaderboards[category] = []
			categorizedLeaderboards[category].push(leaderboard)
		}
	}

	// move misc to end by removing and readding it
	const misc = categorizedLeaderboards.misc
	delete categorizedLeaderboards.misc
	categorizedLeaderboards.misc = misc

	return categorizedLeaderboards
}

/** Fetch the raw names for the slayer leaderboards */
export async function fetchSlayerLeaderboards(): Promise<string[]> {
	const rawSlayerNames = await constants.fetchSlayers()
	let leaderboardNames: string[] = [
		'slayer_total_xp',
		'slayer_total_kills'
	]

	// we use the raw names (zombie, spider, wolf) instead of the clean names (revenant, tarantula, sven) because the raw names are guaranteed to never change
	for (const slayerNameRaw of rawSlayerNames) {
		leaderboardNames.push(`slayer_${slayerNameRaw}_total_xp`)
		leaderboardNames.push(`slayer_${slayerNameRaw}_total_kills`)
		for (let slayerTier = 1; slayerTier <= SLAYER_TIERS[slayerNameRaw]; slayerTier++) {
			leaderboardNames.push(`slayer_${slayerNameRaw}_${slayerTier}_kills`)
		}
	}

	return leaderboardNames
}

async function fetchHarpLeaderboards(): Promise<string[]> {
	const harpSongs = await constants.fetchHarpSongs()
	const leaderboardNames: string[] = []

	for (const songId of harpSongs) {
		leaderboardNames.push(`harp_${songId}_completions`)
		leaderboardNames.push(`harp_${songId}_perfect_completions`)
	}

	return leaderboardNames
}

async function fetchFarmingContestLeaderboards(): Promise<string[]> {
	const leaderboardNames: string[] = []

	leaderboardNames.push(`farming_contests_participated`)
	leaderboardNames.push(`farming_contests_top_1`)
	for (const crop of await constants.fetchCrops()) {
		leaderboardNames.push(`farming_contests_participated_${crop}`)
		leaderboardNames.push(`farming_contests_top_1_${crop}`)
		leaderboardNames.push(`farming_contests_highest_score_${crop}`)
	}

	return leaderboardNames
}

/** Fetch the names of all the leaderboards that rank members */
export async function fetchAllMemberLeaderboardAttributes(): Promise<string[]> {
	return [
		// we use the raw stat names rather than the clean stats in case hypixel adds a new stat and it takes a while for us to clean it
		...await constants.fetchStats(),

		// collection leaderboards
		...(await constants.fetchCollections()).map(value => `collection_${cleanItemId(value)}`),

		// skill leaderboards
		...(await constants.fetchSkills()).map(value => `skill_${value}`),

		// slayer leaderboards
		...await fetchSlayerLeaderboards(),

		// harp leaderboards
		...await fetchHarpLeaderboards(),

		// farming contest leaderboards
		...await fetchFarmingContestLeaderboards(),

		'fairy_souls',
		'first_join',
		'last_save',
		'purse',
		'visited_zones',
		'leaderboards_count',
		'top_1_leaderboards_count',
		'fastest_coop_join',
		'slowest_coop_join',
		'fastest_target_practice'
	]
}

/** Fetch the names of all the leaderboards that rank profiles */
async function fetchAllProfileLeaderboardAttributes(): Promise<string[]> {
	return [
		'unique_minions'
	]
}

function isLeaderboardReversed(name: string): boolean {
	for (const leaderboardMatch of reversedLeaderboards) {
		let trailingEnd = leaderboardMatch[0] === '_'
		let trailingStart = leaderboardMatch.slice(-1) === '_'
		if (
			(trailingStart && name.startsWith(leaderboardMatch))
			|| (trailingEnd && name.endsWith(leaderboardMatch))
			|| (name == leaderboardMatch)
		)
			return true
	}
	return false
}

/** A set of names of the raw leaderboards that are currently being fetched. This is used to make sure two leaderboads aren't fetched at the same time */
const fetchingRawLeaderboardNames: Set<string> = new Set()

async function fetchMemberLeaderboardRaw(name: string): Promise<MemberRawLeaderboardItem[]> {
	if (!client) throw Error('Client isn\'t initialized yet')

	if (cachedRawLeaderboards.has(name))
		return cachedRawLeaderboards.get(name) as MemberRawLeaderboardItem[]

	// if it's currently being fetched, check every 100ms until it's in cachedRawLeaderboards
	if (fetchingRawLeaderboardNames.has(name) && !cachedRawLeaderboards.get(name)) {
		while (true) {
			await sleep(100)
			if (cachedRawLeaderboards.has(name))
				return cachedRawLeaderboards.get(name) as MemberRawLeaderboardItem[]
		}
	}

	// typescript forces us to make a new variable and set it this way because it gives an error otherwise
	const query = {}
	query[`stats.${name}`] = { '$exists': true, '$ne': NaN }

	const sortQuery: any = {}
	sortQuery[`stats.${name}`] = isLeaderboardReversed(name) ? 1 : -1

	fetchingRawLeaderboardNames.add(name)

	if (debug) console.debug(`Fetching leaderboard ${name} from database...`)
	try {
		const leaderboardRaw: MemberRawLeaderboardItem[] = (await memberLeaderboardsCollection
			.find(query)
			.sort(sortQuery)
			.limit(LEADERBOARD_MAX)
			.toArray())
			.map((i: DatabaseMemberLeaderboardItem): MemberRawLeaderboardItem => {
				return {
					profile: i.profile,
					uuid: i.uuid,
					color: i.color,
					username: i.username,
					value: i.stats[name]
				}
			})
		fetchingRawLeaderboardNames.delete(name)
		cachedRawLeaderboards.set(name, leaderboardRaw)
		return leaderboardRaw
	} catch (e) {
		// if it fails while fetching, remove it from fetchingRawLeaderboardNames
		fetchingRawLeaderboardNames.delete(name)
		if (debug) console.debug(`Failed getting leaderboard ${name}!`)
		throw e
	}
}

async function fetchProfileLeaderboardRaw(name: string): Promise<ProfileRawLeaderboardItem[]> {
	if (cachedRawLeaderboards.has(name))
		return cachedRawLeaderboards.get(name) as ProfileRawLeaderboardItem[]

	// if it's currently being fetched, check every 100ms until it's in cachedRawLeaderboards
	if (fetchingRawLeaderboardNames.has(name)) {
		while (true) {
			await sleep(100)
			if (cachedRawLeaderboards.has(name))
				return cachedRawLeaderboards.get(name) as ProfileRawLeaderboardItem[]
		}
	}

	// typescript forces us to make a new variable and set it this way because it gives an error otherwise
	const query = {}
	query[`stats.${name}`] = { '$exists': true, '$ne': NaN }

	const sortQuery: any = {}
	sortQuery[`stats.${name}`] = isLeaderboardReversed(name) ? 1 : -1

	fetchingRawLeaderboardNames.add(name)
	try {
		const leaderboardRaw: ProfileRawLeaderboardItem[] = (await profileLeaderboardsCollection
			.find(query)
			.sort(sortQuery)
			.limit(LEADERBOARD_MAX)
			.toArray())
			.map((i: DatabaseProfileLeaderboardItem): ProfileRawLeaderboardItem => {
				return {
					players: i.players,
					colors: i.colors,
					usernames: i.usernames,
					uuid: i.uuid,
					value: i.stats[name]
				}
			})
		fetchingRawLeaderboardNames.delete(name)

		cachedRawLeaderboards.set(name, leaderboardRaw)
		return leaderboardRaw
	} catch (e) {
		// if it fails while fetching, remove it from fetchingRawLeaderboardNames
		fetchingRawLeaderboardNames.delete(name)
		throw e
	}
}

interface MemberLeaderboard {
	name: string
	unit: string | null
	list: MemberLeaderboardItem[]
	info?: string
}

interface ProfileLeaderboard {
	name: string
	unit: string | null
	list: ProfileLeaderboardItem[]
	info?: string
}

interface LeaderboardBasicPlayer {
	uuid: string
	username: string | undefined
	rank: {
		color: string
	}
}

/** Fetch a leaderboard that ranks members, as opposed to profiles */
export async function fetchMemberLeaderboard(name: string): Promise<MemberLeaderboard> {
	const leaderboardRaw = await fetchMemberLeaderboardRaw(name)

	const leaderboard: MemberLeaderboardItem[] = []
	for (const i of leaderboardRaw) {
		leaderboard.push({
			player: {
				uuid: i.uuid,
				username: i.username,
				rank: {
					color: (i.color ? minecraftColorCodes[i.color] : null) ?? minecraftColorCodes[RANK_COLORS.NONE]!,
				},
			},
			profileUuid: i.profile,
			value: i.value
		})
	}
	return {
		name: name,
		unit: getStatUnit(name) ?? null,
		list: leaderboard
	}
}


/** Fetch a leaderboard that ranks profiles, as opposed to members */
export async function fetchProfileLeaderboard(name: string): Promise<ProfileLeaderboard> {
	const leaderboardRaw = await fetchProfileLeaderboardRaw(name)

	const leaderboard: ProfileLeaderboardItem[] = []

	for (const i of leaderboardRaw) {
		const players: LeaderboardBasicPlayer[] = []
		for (const playerUuid of i.players) {
			const player: LeaderboardBasicPlayer = {
				uuid: playerUuid,
				username: i.usernames ? i.usernames[i.players.indexOf(playerUuid)] : undefined,
				rank: {
					color: i.colors ? i.colors[i.players.indexOf(playerUuid)] : minecraftColorCodes[RANK_COLORS.NONE]!
				}
			}
			if (player)
				players.push(player)
		}
		leaderboard.push({
			players: players,
			profileUuid: i.uuid,
			value: i.value
		})
	}

	return {
		name: name,
		unit: getStatUnit(name) ?? null,
		list: leaderboard
	}
}

/** Fetch a leaderboard */
export async function fetchLeaderboard(name: string): Promise<MemberLeaderboard | ProfileLeaderboard> {
	const profileLeaderboards = await fetchAllProfileLeaderboardAttributes()
	let leaderboard: MemberLeaderboard | ProfileLeaderboard
	if (profileLeaderboards.includes(name)) {
		leaderboard = await fetchProfileLeaderboard(name)
	} else {
		leaderboard = await fetchMemberLeaderboard(name)
	}

	if (leaderboardInfos[name])
		leaderboard.info = leaderboardInfos[name]

	return leaderboard
}

interface LeaderboardSpot {
	name: string
	positionIndex: number
	value: number
	unit: string | null
}

/** Get the leaderboard positions a member is on. This may take a while depending on whether stuff is cached */
export async function fetchMemberLeaderboardSpots(player: string, profile: string, lazy = false): Promise<LeaderboardSpot[] | null> {
	let playerUuid: string | undefined
	let profileUuid: string | undefined
	if (isUuid(player)) playerUuid = player
	if (isUuid(profile)) profileUuid = profile

	let fullProfile: CleanFullProfile
	let fullMember: CleanMember
	if (!(lazy && profileUuid)) {
		const fullProfileNullable = await cached.fetchProfile(player, profile)
		if (!fullProfileNullable) return null
		fullProfile = fullProfileNullable
		profileUuid = fullProfile.uuid

		if (!(lazy && playerUuid)) {
			const fullMemberNullable = fullProfile.members.find(m => m.username.toLowerCase() === player.toLowerCase() || m.uuid === player)
			if (!fullMemberNullable) return null
			fullMember = fullMemberNullable
			playerUuid = fullMember.uuid
		}
	}

	let applicableAttributes: StringNumber = {}
	if (!lazy) {
		// update the leaderboard positions for the member
		await updateDatabaseMember(fullMember!, fullProfile!)

		applicableAttributes = await getApplicableMemberLeaderboardAttributes(fullMember!)
	} else {
		const memberDoc = await memberLeaderboardsCollection.findOne({
			uuid: playerUuid,
			profile: profileUuid
		})
		applicableAttributes = memberDoc?.stats ?? {}
	}

	const memberLeaderboardSpots: LeaderboardSpot[] = []

	let leaderboardPromises: Promise<MemberRawLeaderboardItem[]>[] = []
	for (const leaderboardName in applicableAttributes)
		leaderboardPromises.push(fetchMemberLeaderboardRaw(leaderboardName))
	for (const leaderboardName in applicableAttributes) {
		const leaderboard = await leaderboardPromises.shift()!
		const leaderboardPositionIndexByValue = leaderboard.findIndex(i => i.value === applicableAttributes[leaderboardName])
		const leaderboardPositionIndexByUser = leaderboard.findIndex(i => i.uuid === playerUuid && i.profile === profileUuid)
		const leaderboardPositionIndex = leaderboardPositionIndexByValue !== -1 ? leaderboardPositionIndexByValue : leaderboardPositionIndexByUser

		memberLeaderboardSpots.push({
			name: leaderboardName,
			positionIndex: leaderboardPositionIndex,
			value: applicableAttributes[leaderboardName],
			unit: getStatUnit(leaderboardName) ?? null
		})
	}

	memberLeaderboardSpots.sort((a, b) => a.positionIndex - b.positionIndex)

	return memberLeaderboardSpots
}

async function getLeaderboardRequirement(name: string, leaderboardType: 'member' | 'profile'): Promise<{ top_100: number | null, top_1: number | null }> {
	let leaderboard: MemberRawLeaderboardItem[] | ProfileRawLeaderboardItem[]
	if (leaderboardType === 'member')
		leaderboard = await fetchMemberLeaderboardRaw(name)
	else if (leaderboardType === 'profile')
		leaderboard = await fetchProfileLeaderboardRaw(name)

	// if there's more than 100 items, return the 100th. if there's less, return null
	return {
		top_100: leaderboard![LEADERBOARD_MAX - 1]?.value ?? null,
		top_1: leaderboard![1]?.value ?? null
	}
}

/** Get the attributes for the member, but only ones that would put them on the top 100 for leaderboards */
async function getApplicableMemberLeaderboardAttributes(member: CleanMember): Promise<StringNumber> {
	const leaderboardAttributes = getMemberLeaderboardAttributes(member)
	const applicableAttributes = {}
	const applicableTop1Attributes = {}

	for (const [leaderboard, attributeValue] of Object.entries(leaderboardAttributes)) {
		const requirement = await getLeaderboardRequirement(leaderboard, 'member')
		const leaderboardReversed = isLeaderboardReversed(leaderboard)
		if (
			(requirement.top_100 === null)
			|| (
				leaderboardReversed ? attributeValue < requirement.top_100 : attributeValue > requirement.top_100)
		) {
			applicableAttributes[leaderboard] = attributeValue
		}
		if (
			(requirement.top_1 === null)
			|| (leaderboardReversed ? attributeValue < requirement.top_1 : attributeValue > requirement.top_1)
		) {
			applicableTop1Attributes[leaderboard] = attributeValue
		}
	}

	// add the "leaderboards count" attribute
	const leaderboardsCount: number = Object.keys(applicableAttributes).length
	const leaderboardsCountRequirement = await getLeaderboardRequirement('leaderboards_count', 'member')

	if (
		leaderboardsCount > 0
		&& (
			(leaderboardsCountRequirement.top_100 === null)
			|| (leaderboardsCount > leaderboardsCountRequirement.top_100)
		)
	)
		applicableAttributes['leaderboards_count'] = leaderboardsCount

	// add the "first leaderboards count" attribute
	const top1LeaderboardsCount: number = Object.keys(applicableTop1Attributes).length
	const top1LeaderboardsCountRequirement = await getLeaderboardRequirement('top_1_leaderboards_count', 'member')

	if (
		top1LeaderboardsCount > 0
		&& (
			(top1LeaderboardsCountRequirement.top_100 === null)
			|| (top1LeaderboardsCount > top1LeaderboardsCountRequirement.top_100)
		)
	)
		applicableAttributes['top_1_leaderboards_count'] = top1LeaderboardsCount
	return applicableAttributes
}

/** Get the attributes for the profile, but only ones that would put them on the top 100 for leaderboards */
async function getApplicableProfileLeaderboardAttributes(profile: CleanFullProfile): Promise<StringNumber> {
	const leaderboardAttributes = getProfileLeaderboardAttributes(profile)
	const applicableAttributes = {}
	const applicableTop1Attributes = {}

	for (const [leaderboard, attributeValue] of Object.entries(leaderboardAttributes)) {
		const requirement = await getLeaderboardRequirement(leaderboard, 'profile')
		const leaderboardReversed = isLeaderboardReversed(leaderboard)
		if (
			(requirement.top_100 === null)
			|| (
				leaderboardReversed ? attributeValue < requirement.top_100 : attributeValue > requirement.top_100
					&& attributeValue !== 0
			)
		) {
			applicableAttributes[leaderboard] = attributeValue
		}
		if (
			(requirement.top_1 === null)
			|| (
				leaderboardReversed ? attributeValue < requirement.top_1 : attributeValue > requirement.top_1
					&& attributeValue !== 0
			)
		) {
			applicableTop1Attributes[leaderboard] = attributeValue
		}
	}

	return applicableAttributes
}

/**
 * Make sure there's no lingering profiles from when a player's profile was
 * deleted. This only makes one database call if there's no profiles to delete.
 */
export async function removeDeletedProfilesFromLeaderboards(memberUuid: string, profilesUuids: string[]) {
	if (!client) return

	const leaderboardProfilesInDatabase = (await (await memberLeaderboardsCollection.find({
		uuid: memberUuid,
	})).toArray())

	for (const leaderboardProfile of leaderboardProfilesInDatabase) {
		if (!profilesUuids.includes(leaderboardProfile.profile)) {
			await memberLeaderboardsCollection.deleteOne({
				uuid: memberUuid,
				profile: leaderboardProfile.profile
			})
			if (debug)
				console.log(`Profile ${leaderboardProfile.profile} (member ${memberUuid}) was deleted but was still in leaderboards database, removed.`)

			for (const leaderboardName in leaderboardProfile.stats)
				// we want to refresh the leaderboard so we just remove the cache
				cachedRawLeaderboards.delete(leaderboardName)
		}
	}
}

/** Update the member's leaderboard data on the server if applicable */
export async function updateDatabaseMember(member: CleanMember, profile: CleanFullProfile): Promise<void> {
	if (!client) return // the db client hasn't been initialized
	if (debug) console.debug('updateDatabaseMember', member.username)
	// the member's been updated too recently, just return
	if (recentlyUpdated.get(profile.uuid + member.uuid)) return
	// store the member in recentlyUpdated so it cant update for 3 more minutes
	recentlyUpdated.set(profile.uuid + member.uuid, true)

	if (debug) console.debug('adding member to leaderboards', member.username)

	if (member.rawHypixelStats)
		constants.addStats(Object.keys(member.rawHypixelStats))

	if (debug) console.debug('done constants..')

	const leaderboardAttributes = member.left ? {} : await getApplicableMemberLeaderboardAttributes(member)

	if (debug) console.debug('done getApplicableMemberLeaderboardAttributes..', member.username, profile.name)

	if (Object.values(leaderboardAttributes).length > 0) {
		await memberLeaderboardsCollection.updateOne(
			{
				uuid: member.uuid,
				profile: profile.uuid
			},
			{
				'$set': {
					color: member.rank.color ? (letterFromColorCode(member.rank.color) ?? '') : '',
					username: member.username,
					stats: leaderboardAttributes,
					last_updated: new Date()
				}
			},
			{ upsert: true }
		)
	} else {
		// no leaderboard attributes, delete them!
		await memberLeaderboardsCollection.deleteOne({
			uuid: member.uuid,
			profile: profile.uuid
		})
	}

	for (const [attributeName, attributeValue] of Object.entries(leaderboardAttributes)) {
		const existingRawLeaderboard = await fetchMemberLeaderboardRaw(attributeName)
		const leaderboardReverse = isLeaderboardReversed(attributeName)

		const newRawLeaderboard = existingRawLeaderboard
			// remove the player from the leaderboard, if they're there
			.filter(value => value.uuid !== member.uuid || value.profile !== profile.uuid)
			.concat([{
				value: attributeValue,
				uuid: member.uuid,
				profile: profile.uuid,
				color: member.rank.color ? (letterFromColorCode(member.rank.color) ?? '') : '',
				username: member.username
			}])
			.sort((a, b) => leaderboardReverse ? a.value - b.value : b.value - a.value)
			.slice(0, 100)
		cachedRawLeaderboards.set(attributeName, newRawLeaderboard)
	}

	if (debug) console.debug('added member to leaderboards', leaderboardAttributes, member.username)
}

/**
 * Update the profiles's leaderboard data on the server if applicable.
 * This will not also update the members, you have to call updateDatabaseMember separately for that
 */
export async function updateDatabaseProfile(profile: CleanFullProfile): Promise<void> {
	if (!client) return // the db client hasn't been initialized
	if (debug) console.debug('updateDatabaseProfile', profile.name)

	// the profile's been updated too recently, just return
	if (recentlyUpdated.get(profile.uuid + 'profile'))
		return
	// store the profile in recentlyUpdated so it cant update for 3 more minutes
	recentlyUpdated.set(profile.uuid + 'profile', true)

	if (debug) console.debug('adding profile to leaderboards', profile.name)

	const leaderboardAttributes = await getApplicableProfileLeaderboardAttributes(profile)

	if (debug) console.debug('done getApplicableProfileLeaderboardAttributes..', leaderboardAttributes, profile.name)

	if (leaderboardAttributes.length > 0) {
		await profileLeaderboardsCollection.updateOne(
			{
				uuid: profile.uuid
			},
			{
				'$set': {
					players: profile.members.map(p => p.uuid),
					colors: profile.members.map(p => p.rank.color ? (letterFromColorCode(p.rank.color) ?? '') : ''),
					usernames: profile.members.map(p => p.username),
					stats: leaderboardAttributes,
					last_updated: new Date()
				}
			},
			{ upsert: true }
		)

	} else {
		// no leaderboard attributes, delete them!
		await profileLeaderboardsCollection.deleteOne({
			uuid: profile.uuid,
			profile: profile.uuid
		})
	}


	// add the profile to the cached leaderboard without having to refetch it
	for (const [leaderboardName, attributeValue] of Object.entries(leaderboardAttributes)) {
		const existingRawLeaderboard = await fetchProfileLeaderboardRaw(leaderboardName)
		const leaderboardReverse = isLeaderboardReversed(leaderboardName)

		const newRawLeaderboard = existingRawLeaderboard
			// remove the player from the leaderboard, if they're there
			.filter(value => value.uuid !== profile.uuid)
			.concat([{
				value: attributeValue,
				uuid: profile.uuid,
				players: profile.members.map(p => p.uuid),
				colors: profile.members.map(p => p.rank.color ? (letterFromColorCode(p.rank.color) ?? '') : ''),
				usernames: profile.members.map(p => p.username),
			}])
			.sort((a, b) => leaderboardReverse ? a.value - b.value : b.value - a.value)
			.slice(0, 100)
		cachedRawLeaderboards.set(leaderboardName, newRawLeaderboard)
	}

	if (debug) console.debug('added profile to leaderboards', profile.name, leaderboardAttributes)
}

export const leaderboardUpdateMemberQueue = new Queue({
	concurrent: 2,
	interval: 50
})
export const leaderboardUpdateProfileQueue = new Queue({
	concurrent: 1,
	interval: 500
})

/** Queue an update for the member's leaderboard data on the server if applicable */
export function queueUpdateDatabaseMember(member: CleanMember, profile: CleanFullProfile): void {
	if (recentlyQueued.get(profile.uuid + member.uuid)) return
	else recentlyQueued.set(profile.uuid + member.uuid, true)
	leaderboardUpdateMemberQueue.enqueue(async () => await updateDatabaseMember(member, profile))
}

/** Queue an update for the profile's leaderboard data on the server if applicable */
export function queueUpdateDatabaseProfile(profile: CleanFullProfile): void {
	if (recentlyQueued.get(profile.uuid + 'profile')) return
	else recentlyQueued.set(profile.uuid + 'profile', true)
	leaderboardUpdateProfileQueue.enqueue(async () => await updateDatabaseProfile(profile))
}


/**
 * Remove leaderboard attributes for members that wouldn't actually be on the leaderboard. This saves a lot of storage space
 */
async function removeBadMemberLeaderboardAttributes(): Promise<void> {
	const leaderboards: string[] = await fetchAllMemberLeaderboardAttributes()
	// shuffle so if the application is restarting many times itll still be useful

	for (const leaderboard of shuffle(leaderboards)) {
		// wait 10 seconds so it doesnt use as much ram
		await sleep(10 * 1000)

		const unsetValue = {}
		unsetValue[leaderboard] = ''
		const filter = {}
		const requirement = await getLeaderboardRequirement(leaderboard, 'member')
		const leaderboardReversed = isLeaderboardReversed(leaderboard)
		if (requirement !== null) {
			filter[`stats.${leaderboard}`] = {
				'$lt': leaderboardReversed ? undefined : requirement,
				'$gt': leaderboardReversed ? requirement : undefined
			}
			await memberLeaderboardsCollection.updateMany(
				filter,
				{ '$unset': unsetValue }
			)
		}
	}

	if (debug)
		console.log('Deleted profiles that have no stats from leaderboards')
	await memberLeaderboardsCollection.deleteMany({ stats: {} })
	await profileLeaderboardsCollection.deleteMany({ stats: {} })
	if (debug)
		console.log('Finished deleted profiles that have no stats from leaderboards')
}

export let finishedCachingRawLeaderboards = false

/** Fetch all the leaderboards, used for caching. Don't call this often! */
async function fetchAllLeaderboards(): Promise<void> {
	const leaderboards: string[] = await fetchAllMemberLeaderboardAttributes()

	if (debug) console.debug('Caching raw leaderboards!')

	let concurrentlyFetching = 0

	for (const leaderboard of shuffle(leaderboards)) {
		let fetchLeaderboardPromise = fetchMemberLeaderboardRaw(leaderboard)
		concurrentlyFetching++
		if (concurrentlyFetching > 10) {
			await fetchLeaderboardPromise
			concurrentlyFetching--
		} else
			fetchLeaderboardPromise.then(() => concurrentlyFetching--)
	}
	finishedCachingRawLeaderboards = true
}

export async function createSession(refreshToken: string, userData: discord.DiscordUser): Promise<string> {
	const sessionId = uuid4()
	await sessionsCollection?.insertOne({
		_id: sessionId,
		refresh_token: refreshToken,
		discord_user: {
			id: userData.id,
			name: userData.username + '#' + userData.discriminator
		},
		lastUpdated: new Date()
	})
	return sessionId
}

export async function fetchSession(sessionId: string): Promise<WithId<SessionSchema> | null> {
	return await sessionsCollection?.findOne({ _id: sessionId as any })
}


export async function deleteSession(sessionId: string) {
	return await sessionsCollection?.deleteOne({ _id: sessionId as any })
}

export async function fetchAccount(minecraftUuid: string): Promise<WithId<AccountSchema> | null> {
	return await accountsCollection?.findOne({ minecraftUuid })
}

export async function fetchAccountFromDiscord(discordId: string): Promise<WithId<AccountSchema> | null> {
	return await accountsCollection?.findOne({ discordId })
}

export async function updateAccount(discordId: string, schema: AccountSchema) {
	if (schema.minecraftUuid) {
		const existingAccount = await accountsCollection?.findOne({ minecraftUuid: schema.minecraftUuid })
		// if the discord ids don't match, change the discord id of the existing account
		if (existingAccount && existingAccount.discordId !== discordId) {
			await accountsCollection?.updateOne(
				{ minecraftUuid: schema.minecraftUuid },
				{ '$set': { discordId } }
			)
		}
	}
	await accountsCollection?.updateOne({
		discordId
	}, { $set: schema }, { upsert: true })
}

function toItemAuctionsSchema(i: ItemAuctionsSchemaBson): ItemAuctionsSchema {
	return {
		id: i._id,
		sbId: i.sbId,
		auctions: i.auctions.map(a => {
			return {
				...a,
				id: a.id.toString('hex'),
			}
		}),
	}
}

function toItemAuctionsSchemaBson(i: ItemAuctionsSchema): ItemAuctionsSchemaBson {
	return {
		_id: i.id,
		sbId: i.sbId,
		auctions: i.auctions.map(a => {
			return {
				...a,
				id: createUuid(a.id)
			}
		}),
		// we sort by oldestDate to get the volume sold, but we don't want brand new items with like no data having a high frequency
		oldestDate: i.auctions.length > 10 ? i.auctions[0]?.ts ?? 0 : 0
	}
}

/** Fetch all the Item Auctions for the item ids in the given array. */
export async function fetchItemsAuctions(itemIds: string[]): Promise<ItemAuctionsSchema[]> {
	const auctions = await itemAuctionsCollection?.find({
		_id: { $in: itemIds }
	}).sort('oldestDate', -1).toArray()
	return auctions.map(toItemAuctionsSchema)
}


/** Fetch all the Item Auctions for the item ids in the given array. */
export async function fetchPaginatedItemsAuctions(skip: number, limit: number): Promise<ItemAuctionsSchema[]> {
	const auctions = await itemAuctionsCollection?.find({}).sort('oldestDate', -1).skip(skip).limit(limit).toArray()
	return auctions.map(toItemAuctionsSchema)
}

export async function updateItemAuction(auction: ItemAuctionsSchema) {
	await itemAuctionsCollection?.updateOne({
		_id: auction.id,
	}, { $set: toItemAuctionsSchemaBson(auction) }, { upsert: true })
}

/**
 * Fetches the SkyBlock ids of all the items in the auctions database. This method is slow and should be cached!
 */
export async function fetchItemsAuctionsIds(skyblockIds: boolean = false): Promise<string[] | undefined> {
	if (!itemAuctionsCollection) return undefined
	const docs = await itemAuctionsCollection?.aggregate([
		{ $sort: { oldestDate: -1 } },
		// this removes everything except the _id
		{ $project: skyblockIds ? { _id: false, sbId: true } : { _id: true } }
	]).toArray()
	return skyblockIds ? docs.filter(r => r.sbId).map(r => r.sbId) : docs.map(r => r._id)
}


export async function fetchServerStatus() {
	return await database.admin().serverStatus()
}

export async function fetchServerStats() {
	return await database.stats()
}

// make sure it's not in a test
console.log('global.isTest', globalThis.isTest)
if (!globalThis.isTest) {
	connect().then(() => {
		// when it connects, cache the leaderboards and remove bad members
		removeBadMemberLeaderboardAttributes()
		// cache leaderboards on startup so its faster later on
		fetchAllLeaderboards()
		// cache leaderboard players again every 4 hours
		setInterval(fetchAllLeaderboards, 4 * 60 * 60 * 1000)
	})
}