Files
cod-backend/Sources/App/Controllers/StatsController.swift
2021-10-31 00:01:27 -05:00

1136 lines
43 KiB
Swift

import Fluent
import Vapor
struct CODDate {
let month:Int
let year:Int
let day: Int
let hour:Int
let minute:Int
}
struct StatsController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let statsRoute = routes.grouped("cod-tracker","api", "stats")
statsRoute.get("allMatches", use: index)
statsRoute.get("totalWins", use: totalWins)
statsRoute.get("totalLosses", use: totalLosses)
statsRoute.get("overall", use: overall)
statsRoute.get("allDaily", use: allDaily)
statsRoute.post("logMatch", use: logMatch)
statsRoute.get("history","page",":page", use: history)
statsRoute.get("history", use: history)
statsRoute.get("maps", use: mapRecords)
statsRoute.get("maps","game",":game","competitive",":competitive",use: mapRecords)
statsRoute.get("maps","game",":game","competitive",":competitive", "gamemode", ":gamemode",use: mapRecords)
statsRoute.get("dashboard", use: dashboard)
statsRoute.get("recalculate", use: recalc)
statsRoute.get("stats","q",":query", use: history)
}
func dashboard(db: Database) throws -> EventLoopFuture<DashboardStats> {
let statistics = WinLossRecords.query(on: db).all()
let adamAffectedMatches = Match.query(on: db).filter(\.$finalKillRuinedPlayerId == 6).count()
let totalMWGames = Match.query(on: db).filter(\.$codGame == "mw").count()
return (statistics.and(adamAffectedMatches).and(totalMWGames)).map { arg -> (DashboardStats) in
let (((statistics, adamAffectedMatches), totalMWGames)) = arg
// return statistics.map { statistics in
return DashboardStats(dashboardItems: (statistics.map({ statisticItem in
let title = statisticItem.title
var title2:String? = ""
var content1 = ""
var content2 = ""
var sortOrder = 0
if statisticItem.codTrackerId == "no_hyder_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 100
}
else if statisticItem.codTrackerId == "mw_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 20
}
else if statisticItem.codTrackerId == "mw_six_players"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 60
}
else if statisticItem.codTrackerId == "2021_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 50
}
else if statisticItem.codTrackerId == "bocw_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 30
}
else if statisticItem.codTrackerId == "with_hyder_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 110
}
else if statisticItem.codTrackerId == "mw_five_players"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 70
}
else if statisticItem.codTrackerId == "casual_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 40
}
else if statisticItem.codTrackerId == "overall_four_players"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 80
}
else if statisticItem.codTrackerId == "overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 10
}
else if statisticItem.codTrackerId == "2020_overall"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 90
}
else if statisticItem.codTrackerId == "bocw_nuketown_halloween"{
title2 = "Ratio"
content1 = "\(statisticItem.wins)-\(statisticItem.losses)"
content2 = Utils.getRatio(wins: statisticItem.wins, losses: statisticItem.losses)
sortOrder = 41
}
else {
}
return
DashboardItem(codTrackerId:statisticItem.codTrackerId, title: title, content: content1, title2: title2, content2: content2, sortOrder: sortOrder, backgroundColor: statisticItem.codTrackerId == "bocw_nuketown_halloween" ? "FFA500" : "004999")
} ) +
[
DashboardItem(codTrackerId: "adam_ruined_final_kills", title: "Final Kills Ruined by Adam", content: "\(adamAffectedMatches + 7)", title2: "", content2: "",sortOrder: 1000),
DashboardItem(codTrackerId:"total_mw_games", title: "Total MW Games", content: "\(totalMWGames)", title2: "", content2: "", sortOrder: -10),
]
).sorted{$0.sortOrder < $1.sortOrder}
)
}
}
func dashboard(req: Request) throws -> EventLoopFuture<DashboardStats> {
return try dashboard(db: req.db)
}
func history(req: Request) throws -> EventLoopFuture<MatchHistory> {
if let page = req.parameters.get("page", as: Int.self) {
return Match.query(on: req.db).count().flatMap { (totalMatches) -> EventLoopFuture<MatchHistory> in
let startRecord = min (page * 20, totalMatches)
let lastRecord = min (startRecord + 20, totalMatches)
return Match.query(on: req.db).sort(\.$date, .descending).range(startRecord..<lastRecord).all().map { (matches) -> (MatchHistory) in
return MatchHistory(total:totalMatches, matches: matches, hasMorePages: lastRecord < totalMatches)
}
}
}
else {
return Match.query(on: req.db).count().flatMap { (totalMatches) -> EventLoopFuture<MatchHistory> in
return Match.query(on: req.db).sort(\.$date, .descending).limit(20).all().map { (matches) -> (MatchHistory) in
return MatchHistory(total:totalMatches, matches: matches, hasMorePages: totalMatches > 20)
}
}
}
}
func logMatch(req: Request) throws -> EventLoopFuture<Match> {
let newMatch = try req.content.decode(Match.self)
return newMatch.save(on: req.db).map { newMatch}
}
func getCountedMatches(matches:[Match]) -> Stats{
let countedMatches = matches.filter {
return self.shouldCountMatch(match: $0)
}
let totals = countedMatches.reduce([0,0]) { (totals, match) -> [Int] in
if match.win == true {
return [totals[0] + 1, totals[1]]
}
else {
return [totals[0], totals[1] + 1]
}
}
let winCount = totals[0]
let lossCount = totals[1]
return Stats( totalWins: Int(winCount), totalLosses: Int(lossCount))
}
func getAllMatches(matches:[Match]) -> Stats{
let totals = matches.reduce([0,0]) { (totals, match) -> [Int] in
if match.win == true {
return [totals[0] + 1, totals[1]]
}
else {
return [totals[0], totals[1] + 1]
}
}
let winCount = totals[0]
let lossCount = totals[1]
return Stats( totalWins: Int(winCount), totalLosses: Int(lossCount))
}
func getStatsWithMostRecentDailyRecord(sortedMatches:[Match], game:String? = nil) -> StatsWithMostRecentDailyRecord {
let stats = getCountedMatches(matches: sortedMatches)
//print ("MRR STATS \(Date().timeIntervalSince(startTime))")
let mostRecentDailyStats = self.mostRecentDailyStats(matches: sortedMatches, game: game)
//print ("MRR DAILY \(Date().timeIntervalSince(startTime))")
let ret = StatsWithMostRecentDailyRecord(winLoss: stats.winLossRatio, totalWins: stats.totalWins, totalLosses: stats.totalLosses, mostRecentRecord:"\(mostRecentDailyStats.totalWins)-\(mostRecentDailyStats.totalLosses)")
return ret
}
func mostRecentDailyStats (matches:[Match], game:String? = nil) -> Stats{
let daysPlayed = getDaysPlayed(sortedMatches: matches)
let lastDayPlayed = daysPlayed.last
//print ("MDD days played \(Date().timeIntervalSince(startTime))")
return getCountedMatches(matches: matches.filter({ (match) -> Bool in
var shouldInclude =
match.date.day == lastDayPlayed?.day &&
match.date.month == lastDayPlayed?.month &&
match.date.year == lastDayPlayed?.year &&
self.shouldCountMatch(match: match)
if let game = game {
shouldInclude = shouldInclude && match.codGame == game
}
return shouldInclude
}))
}
private func shouldCountMatch (match:Match) -> Bool {
let isColdWar = match.codGame == "bocw"
let numberOfPlayers = self.numberOfPlayers(match: match)
if match.competitive == false {
return false
}
if isColdWar {
if numberOfPlayers == 0 {
return true
}
else if numberOfPlayers > 4 {
return true
}
else {
return false
}
}
else {
if numberOfPlayers > 4 || numberOfPlayers == 0 {
return true
}
else if numberOfPlayers == 4 {
return match.date < Date(timeIntervalSince1970: 1612159200)
} // February 1 2021
else {
return false
}
}
}
func getStatsForYear(year:Int, db: Database) -> EventLoopFuture<Stats>{
// Specify date components
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = 1
dateComponents.day = 1
dateComponents.timeZone = TimeZone(abbreviation: "EST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 0
// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let startDate = userCalendar.date(from: dateComponents)
var endDateComponenents = DateComponents()
endDateComponenents.year = year + 1
endDateComponenents.month = 1
endDateComponenents.day = 1
endDateComponenents.timeZone = TimeZone(abbreviation: "EST") // Japan Standard Time
endDateComponenents.hour = 8
endDateComponenents.minute = 0
let endDate = userCalendar.date(from: endDateComponenents)
return Match.query(on: db).filter(\.$date > startDate!).filter(\.$date < endDate!).all().map { (matches) -> (Stats) in
return self.getCountedMatches(matches: matches)
}
}
private func numberOfPlayers(match:Match) -> Int {
return match.players?.components(separatedBy: ",").count ?? 0
}
private func getDaysPlayed(sortedMatches:[Match]) -> [CODDate] {
let dates = sortedMatches.suffix(30).map { (match) -> CODDate in
return CODDate(month: match.date.month, year: match.date.year, day: match.date.day, hour: match.date.hour, minute: match.date.minute)
}
return dates.reduce([CODDate]()) { (datesPlayed, codDate) -> [CODDate] in
if datesPlayed.contains(where: { (existingDate) -> Bool in
if codDate.month == existingDate.month && codDate.year == existingDate.year && existingDate.day == codDate.day{
return true
}
return false
}){
return datesPlayed
}else {
return datesPlayed + [codDate]
}
}
}
func getCumulativeWinLossRatios(matches:[Match]) -> [DataPoint] {
let daysPlayed = getDaysPlayed(sortedMatches: matches)
var cumulativeRatios : [DataPoint] = []
var cumulativeWins:Int = 0
var cumulativeLosses:Int = 0
var dayMatches:[[Match]] = []
var currentDay = daysPlayed.first?.day ?? 0
var currentMonth = daysPlayed.first?.month ?? 0
var currentYear = daysPlayed.first?.year ?? 0
let sortedMatches = matches.sorted { (m1, m2) -> Bool in
return m1.date < m2.date
}
var currentMatches:[Match] = []
for match in sortedMatches {
if match.date.year == currentYear && match.date.month == currentMonth && match.date.day == currentDay {
currentMatches.append(match)
}
else {
dayMatches.append(currentMatches)
currentMatches = [match]
currentDay = match.date.day
currentYear = match.date.year
currentMonth = match.date.month
}
}
for (i, matchGroup) in dayMatches.enumerated() {
let stats = self.getCountedMatches(matches: matchGroup)
cumulativeWins = cumulativeWins + stats.totalWins;
cumulativeLosses = cumulativeLosses + stats.totalLosses;
cumulativeRatios.append( DataPoint(x: Double(i), y: (Double(cumulativeWins) / (Double(cumulativeLosses) )), label: ("\(Utilities.monthToString(month: matchGroup.first!.date.month)) \( matchGroup.first!.date.day)")))
}
return cumulativeRatios
}
func index(req: Request) throws -> EventLoopFuture<[Match]> {
return Match.query(on: req.db).sort(\.$date).all()
}
func totalWins(req: Request) throws -> EventLoopFuture<Int> {
return Match.query(on: req.db)
.filter(\.$win == true)
.count()
}
func totalLosses(req: Request) throws -> EventLoopFuture<Int> {
return Match.query(on: req.db)
.filter(\.$win == false)
.count()
}
func getMarchStats(req:Request) throws -> EventLoopFuture<Stats> {
return getstatsForMonth(year: 2020, month: 03, req: req)
}
func getstatsForMonth(year:Int, month:Int, req: Request) -> EventLoopFuture<Stats>{
let winCount = Match.query(on: req.db)
.filter(\.$date >= getStartOfMonth(month: month, year: year))
.filter(\.$date <= getEndOfMonth(month: month, year: year))
.filter(\.$win == true )
.count()
let lossCount = Match.query(on: req.db)
.filter(\.$date >= getStartOfMonth(month: month, year: year))
.filter(\.$date <= getEndOfMonth(month: month, year: year))
.filter(\.$win == false )
.count()
let combined = winCount.and(lossCount)
return combined.map { (winCount, lossCount) -> (Stats) in
return Stats.init( totalWins: winCount, totalLosses: lossCount)
}
}
func getCasualStats( db: Database) -> EventLoopFuture<Stats>{
return Match.query(on: db).filter(\.$competitive == false).all().map { matches in
return Stats(totalWins: matches.filter{$0.win == true}.count, totalLosses: matches.filter{$0.win == false}.count)
}
}
func getStatsForDay(year:Int, month:Int, day:Int, req: Request) -> EventLoopFuture<Stats>{
let winCount = Match.query(on: req.db)
.filter(\.$date >= getStartOfDay(day:day, month: month, year: year))
.filter(\.$date <= getEndOfDay(day: day, month: month, year: year))
.filter(\.$win == true )
.count()
let lossCount = Match.query(on: req.db)
.filter(\.$date >= getStartOfDay(day:day, month: month, year: year))
.filter(\.$date <= getEndOfDay(day: day, month: month, year: year))
.filter(\.$win == false )
.count()
let combined = winCount.and(lossCount)
return combined.map { (winCount, lossCount) -> (Stats) in
return Stats.init(totalWins: winCount, totalLosses: lossCount)
}
}
func statsForRecent(numberGames:Int, req:Request) -> EventLoopFuture<Stats> {
let winCount = Match.query(on: req.db)
.sort(\.$date)
.range(lower: 0, upper: numberGames)
.filter(\.$win == true )
.count()
let lossCount = Match.query(on: req.db)
.sort(\.$date)
.range(lower: 0, upper: numberGames)
.filter(\.$win == false )
.count()
let combined = winCount.and(lossCount)
return combined.map { (winCount, lossCount) -> (Stats) in
return Stats.init(totalWins: winCount, totalLosses: lossCount)
}
}
private func getStartOfMonth(month:Int, year:Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.timeZone = TimeZone(identifier: "GMT")
components.day = 1
components.month = month
components.year = year
components.hour = 0
components.minute = 0
return calendar.date(from: components)!
}
private func getEndOfMonth(month:Int, year:Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.day = -0
components.timeZone = TimeZone(identifier: "GMT")
components.month = month + 1
components.year = year
components.hour = 23
components.minute = 59
return calendar.date(from: components)!
}
private func getStartOfDay(day:Int, month:Int, year:Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.timeZone = TimeZone(identifier: "GMT")
components.day = day
components.month = month
components.year = year
components.hour = 0
components.minute = 0
return calendar.date(from: components)!
}
private func getEndOfDay(day:Int, month:Int, year:Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.timeZone = TimeZone(identifier: "GMT")
components.day = day
components.month = month
components.year = year
components.hour = 23
components.minute = 59
return calendar.date(from: components)!
}
private func getStartDate() -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.timeZone = TimeZone(identifier: "GMT")
components.day = 10
components.month = 03
components.year = 2020
components.hour = 4
components.minute = 0
return calendar.date(from: components)!
}
private func createDate(day:Int, month:Int, year:Int, hour:Int, minute:Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.timeZone = TimeZone(identifier: "GMT")
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
return calendar.date(from: components)!
}
func mostRecentDailyStats (req:Request) -> EventLoopFuture<Stats>{
return getDaysPlayed(req: req).flatMap { (days) -> (EventLoopFuture<Stats>) in
return self.getStatsForDay(year: days.first?.year ?? 0, month: days.first?.month ?? 0, day: days.first?.day ?? 0, req: req)
}
}
func recalc(req:Request) -> EventLoopFuture<[String:Stats]> {
return forceCalculatedStats(db: req.db)
}
func forceCalculatedStats(db: Database) -> EventLoopFuture<[String:Stats]> {
let statsWithHyder = statsWithPlayer(db: db, playerId: 5)
let statsWithoutHyder = statsWithoutPlayer(db: db, playerId: 5)
let statsFor2020 = getStatsForYear(year: 2020, db: db)
let statsFor2021 = getStatsForYear(year: 2021, db: db)
let hyderFuture = statsWithHyder.and(statsWithoutHyder)
let hyderStats = hyderFuture.map { (withHyder, withoutHyder) -> [Stats] in
return [withHyder, withoutHyder]
}
let casualOverall = getCasualStats(db: db)
let matches = Match.query(on: db).sort( \.$date).all()
return matches.and(hyderStats).and(statsFor2020).and(statsFor2021).and(casualOverall).map { arg -> ([String:Stats]) in
let ((((matches, hyderStats), statsFor2020), statsFor2021), casualOverall) = arg
//print ("got matches \(Date().timeIntervalSince(startTime))")
let queue = DispatchQueue(label: "com.sledsoft.cod-tracker.queue", attributes: .concurrent)
let group = DispatchGroup()
var overallStats:StatsWithMostRecentDailyRecord?
var mwStats:StatsWithMostRecentDailyRecord?
var bocwStats:StatsWithMostRecentDailyRecord?
var mostRecentStats:Stats?
var mwSixPlayers:Stats?
var mwFivePlayers:Stats?
var overallFourPlayers:Stats?
var blackOpsColdWarNuketownHalloween:Stats?
// var mapStats:[Int:Stats]?
// var worstMap:Int?
// var bestMap:Int?
//
group.enter()
queue.async {
overallStats = self.getStatsWithMostRecentDailyRecord(sortedMatches: matches)
group.leave()
}
group.enter()
queue.async {
mwStats = self.getStatsWithMostRecentDailyRecord(sortedMatches: matches.filter({ (match) -> Bool in
return match.codGame == "mw" && self.shouldCountMatch(match: match )
}))
group.leave()
}
group.enter()
queue.async {
bocwStats = self.getStatsWithMostRecentDailyRecord(sortedMatches: matches.filter({ (match) -> Bool in
return match.codGame == "bocw" && self.shouldCountMatch(match: match )
}))
group.leave()
}
group.enter()
queue.async {
overallFourPlayers = self.getAllMatchesByPlayerCount(matches: matches, playerCount: 4) //Feb
group.leave()
}
group.enter()
queue.async {
mwFivePlayers = self.getCountedMatchesByPlayerCount(matches: matches.filter{$0.codGame == "mw"}, playerCount: 5)
group.leave()
}
group.enter()
queue.async {
mwSixPlayers = self.getCountedMatchesByPlayerCount(matches: matches.filter{$0.codGame == "mw"}, playerCount: 6)
group.leave()
}
group.enter()
queue.async {
blackOpsColdWarNuketownHalloween = self.getRecordForMapId(matches: matches.filter{$0.codGame == "bocw"}, mapId: "69")
group.leave()
}
group.wait()
return [
"bocw_nuketown_halloween":Stats(totalWins: blackOpsColdWarNuketownHalloween!.totalWins, totalLosses: blackOpsColdWarNuketownHalloween!.totalLosses),
"mw_overall":Stats(totalWins: mwStats!.totalWins, totalLosses: mwStats!.totalLosses),
"no_hyder_overall":Stats(totalWins: hyderStats[1].totalWins, totalLosses: hyderStats[1].totalLosses),
"with_hyder_overall":Stats(totalWins:hyderStats[0].totalWins, totalLosses: hyderStats[0].totalLosses),
"bocw_overall":Stats(totalWins: bocwStats!.totalWins, totalLosses: bocwStats!.totalLosses),
"2020_overall":Stats(totalWins: statsFor2020.totalWins, totalLosses: statsFor2020.totalLosses),
"2021_overall":Stats(totalWins: statsFor2021.totalWins, totalLosses: statsFor2021.totalLosses),
"mw_six_players":Stats(totalWins: mwSixPlayers!.totalWins, totalLosses: mwSixPlayers!.totalLosses),
"overall_four_players":Stats(totalWins: overallFourPlayers!.totalWins, totalLosses: overallFourPlayers!.totalLosses),
"mw_five_players":Stats(totalWins: mwFivePlayers!.totalWins, totalLosses: mwFivePlayers!.totalLosses),
"overall":Stats(totalWins: overallStats!.totalWins, totalLosses: overallStats!.totalLosses),
"casual_overall":Stats(totalWins: casualOverall.totalWins, totalLosses: casualOverall.totalLosses),
]
}
}
func overall(db: Database) throws -> EventLoopFuture<OverallStats> {
let dashboardStats = try dashboard(db:db)
let matches = Match.query(on: db).sort( \.$date).all()
let mapConfigs = mapConfigs(db: db)
return matches.and(dashboardStats).and(mapConfigs).map { arg -> (OverallStats) in
let ((matches, dashboardStats),mapConfigs) = arg
let queue = DispatchQueue(label: "com.sledsoft.cod-tracker.queue", attributes: .concurrent)
let group = DispatchGroup()
var mapStats:[Int:Stats]?
var worstMap:Int?
var bestMap:Int?
//
group.enter()
queue.async {
mapStats = self.getMapStats(matches: matches,game: "mw", competitive: true)
//print ("maps done \(Date().timeIntervalSince(startTime))")
group.leave()
}
//
group.enter()
queue.async {
let mapStats = self.getMapStats(matches: matches,game: "mw", competitive: true)
bestMap = self.getBestMap(records: mapStats)
group.leave()
}
group.enter()
queue.async {
let mapStats = self.getMapStats(matches: matches,game: "mw", competitive: true)
worstMap = self.getWorstMap(records: mapStats)
group.leave()
}
group.wait()
let dashboardItems:[DashboardItem] =
(dashboardStats.dashboardItems +
[
DashboardItem(codTrackerId:"best_map_overall", title: "Best Map", content: mapConfigs.first{$0.mapId == bestMap}?.name ?? "error", title2: "Ratio", content2: "\(mapStats![bestMap!]!.winLossRatio) \(mapStats![bestMap!]!.record)", sortOrder: 12),
DashboardItem(codTrackerId:"worst_map_overall", title: "Worst Map", content: mapConfigs.first{$0.mapId == worstMap}?.name ?? "error", title2: "Ratio", content2: "\(mapStats![worstMap!]!.winLossRatio) \(mapStats![worstMap!]!.record)",sortOrder: 13),
]).sorted{
$0.sortOrder < $1.sortOrder
}
return OverallStats(dashboardItems: dashboardItems)
}
}
func overall(req: Request) throws -> EventLoopFuture<OverallStats> {
return try overall(db: req.db)
}
func mapConfigs(db: Database) -> EventLoopFuture<[MapConfig]> {
return Map.query(on: db).all().map { map in
return map.map { m in
return m.mapConfig
}
}
}
func mapRecords(req: Request) throws -> EventLoopFuture<[MapRecord]> {
let matches = Match.query(on: req.db).all()
let mapConfigs = mapConfigs(db: req.db)
return matches.and(mapConfigs).map { matches, mapConfigs in
let mapStats:[Int:Stats]
if let game = req.parameters.get("game", as: String.self),
let competitive = req.parameters.get("competitive", as:Bool.self) {
let gameMode = req.parameters.get("gamemode", as:Int.self) ?? -2
mapStats = self.getMapStats(matches: matches,game: game, competitive: competitive, gameMode: gameMode)
}
else {
mapStats = self.getMapStats(matches: matches,game: "mw", competitive: true)
}
let sortedMaps = self.mapsSortedByBest(records: mapStats)
let records = sortedMaps.map { (mapId) -> MapRecord in
return MapRecord(map: mapConfigs.first{$0.mapId == mapId}!, stats: mapStats[mapId]!, ratio:mapStats[mapId]!.winLossRatio)
}
var wins:Double = 0
var loss:Double = 0
for record in records {
//print("\(record.map.name) \(record.stats.record) \(record.ratio)")
wins = wins + Double(record.stats.totalWins)
loss = loss + Double(record.stats.totalLosses)
}
return records
}
//
// return Match.query(on: req.db).all().map { (matches) -> [MapRecord] in
//
//
//
// let mapStats:[Int:Stats]
//
// if let game = req.parameters.get("game", as: String.self),
// let competitive = req.parameters.get("competitive", as:Bool.self) {
//
// let gameMode = req.parameters.get("gamemode", as:Int.self) ?? -2
// mapStats = self.getMapStats(matches: matches,game: game, competitive: competitive, gameMode: gameMode)
//
// }
// else {
// mapStats = self.getMapStats(matches: matches,game: "mw", competitive: true)
// }
//
//
// let sortedMaps = self.mapsSortedByBest(records: mapStats)
//
// let records = sortedMaps.map { (mapId) -> MapRecord in
// return MapRecord(map: MapData.allMaps[mapId]!, stats: mapStats[mapId]!, ratio:mapStats[mapId]!.winLossRatio)
// }
//
// var wins:Double = 0
// var loss:Double = 0
//
// for record in records {
// //print("\(record.map.name) \(record.stats.record) \(record.ratio)")
// wins = wins + Double(record.stats.totalWins)
// loss = loss + Double(record.stats.totalLosses)
//
// }
// return records
// }
}
func mapsSortedByBest (records :[ Int:Stats] ) -> [ Int ] {
return records.keys.sorted { (map1, map2) -> Bool in
return records[map1]?.getRatioDouble() ?? 0.0 < records[map2]?.getRatioDouble() ?? 0.0
}.reversed()
}
func getCountedMatchesByPlayerCount(matches:[Match], playerCount:Int) -> Stats {
return getCountedMatches(matches: matches.filter{$0.playerList.count == playerCount})
}
func getRecordForMapId(matches:[Match], mapId:String) -> Stats {
return getAllMatches(matches: matches.filter{$0.map == mapId})
}
func getAllMatchesByPlayerCount(matches:[Match], playerCount:Int) -> Stats {
return getAllMatches(matches: matches.filter{$0.playerList.count == playerCount})
}
func getBestMap (records :[ Int:Stats] ) -> Int {
let maps = records.keys.sorted { (map1, map2) -> Bool in
return records[map1]?.getRatioDouble() ?? 0.0 < records[map2]?.getRatioDouble() ?? 0.0
}
return maps.last ?? -1
}
func getWorstMap (records :[ Int:Stats] ) -> Int {
let maps = records.keys.sorted { (map1, map2) -> Bool in
return records[map1]?.getRatioDouble() ?? 0.0 < records[map2]?.getRatioDouble() ?? 0.0
}
return maps.first ?? -1
}
func getMapStats(matches:[Match], game:String, competitive:Bool, gameMode:Int = -2) -> [Int:Stats] {
var mapStats:[Int:Stats] = [Int:Stats]()
let filteredMatches = matches
.filter{$0.competitive == competitive}
.filter{$0.codGame == game}
.filter{
if gameMode >= 0 {
return $0.gameMode == gameMode
}
else if gameMode == -2 { // -2 is all for now
return true
}
else {
return true
}
}
for match in filteredMatches {
if competitive == true {
if !shouldCountMatch(match: match){
continue
}
}
if let map = match.map, let mapInt = Int(map) {
if mapStats[mapInt] == nil {
mapStats[mapInt] = Stats(totalWins: 0, totalLosses: 0)
}
if match.win {
mapStats[mapInt]?.totalWins += 1
}
else{
mapStats[mapInt]?.totalLosses += 1
}
}
}
return mapStats
}
func statsWithPlayer(db: Database, playerId:Int) -> EventLoopFuture<Stats> {
return Match.query(on: db)
.filter(\.$players ~~ "\(playerId)")
.all().map { (matches) -> (Stats) in
return self.getCountedMatches(matches: matches)
}
}
func statsWithoutPlayer (db: Database, playerId:Int) -> EventLoopFuture<Stats> {
return Match.query(on: db)
.filter(\.$players !~ "\(playerId)")
.all().map { (matches) -> (Stats) in
return self.getCountedMatches(matches: matches)
}
}
private func getDaysPlayed(req:Request) -> EventLoopFuture<[CODDate]> {
return Match.query(on: req.db).sort(\.$date, .descending).all().map { (matches) -> ([CODDate]) in
return matches.map { (match) -> CODDate in
return CODDate(month: match.date.month, year: match.date.year, day: match.date.day, hour: match.date.hour, minute: match.date.minute)
}.reduce([CODDate]()) { (datesPlayed, codDate) -> [CODDate] in
if datesPlayed.contains(where: { (existingDate) -> Bool in
if codDate.month == existingDate.month && codDate.year == existingDate.year && existingDate.day == codDate.day{
return true
}
return false
}){
return datesPlayed
}else {
return datesPlayed + [codDate]
}
}
}
}
func allDaily(req:Request) -> EventLoopFuture<AllDailyStats>{
return getDaysPlayed(req: req).flatMap { (previousDays) -> (EventLoopFuture<AllDailyStats>) in
func getDailyStats (_ remaining: ArraySlice<CODDate>, allDailyStats: inout [DailyStats], eventLoop: EventLoop) -> EventLoopFuture<[DailyStats]> {
var remaining = remaining
if let first = remaining.popLast() {
return self.getStatsForDay(year: first.year, month: first.month, day:first.day, req: req).flatMap { [remaining, allDailyStats] (stats) -> EventLoopFuture<[DailyStats]> in
var allDailyStats = allDailyStats
let totalWins = allDailyStats.reduce(Double(stats.totalWins)) { (total, dailyStats) -> Double in
return total + Double(dailyStats.stats.totalWins) }
let totalLosses = allDailyStats.reduce(Double(stats.totalLosses)) { (total, dailyStats) -> Double in
return total + Double(dailyStats.stats.totalLosses)
}
allDailyStats.append(DailyStats(day: first.day, month: first.month, year: first.year, stats: stats, cumulativeRatio: self.getRatio(num: totalWins, den: totalLosses)))
return getDailyStats(remaining, allDailyStats:&allDailyStats, eventLoop: eventLoop)
}
} else {
return req.eventLoop.makeSucceededFuture(allDailyStats)
}
}
var stats:[DailyStats] = []
let dailyStats = getDailyStats(Array(previousDays)[0..<previousDays.count], allDailyStats:&stats, eventLoop: req.eventLoop)
return dailyStats.map { (dailyStats) -> AllDailyStats in
return AllDailyStats(dailyStats: dailyStats.filter({ (dailyStats) -> Bool in
if dailyStats.stats.totalWins == 0 && dailyStats.stats.totalLosses == 0 {
return false
}
return true
}).reversed()
)
}
}
}
private func getRatio( num:Double, den:Double) -> String {
var returnString = ""
let deno = (den != 0) ? den : 1
returnString = String((Double(num) / Double(deno)).truncate(places: 2))
if den == 0 {
returnString = returnString + "+"
}
return returnString
}
func getCumulativeWinLossRatios(req:Request) -> EventLoopFuture<[DataPoint]> {
return getDaysPlayed(req: req).flatMap { (previousDays) -> (EventLoopFuture<[DataPoint]>) in
func getRatios (_ remaining: ArraySlice<CODDate>, allDailyStats: inout [DailyStats], cumulativeWinLossRatios: inout [DataPoint], eventLoop: EventLoop) -> EventLoopFuture<[DataPoint]> {
var remaining = remaining
if let first = remaining.popLast() {
return self.getStatsForDay(year: first.year, month: first.month, day:first.day, req: req).flatMap { [remaining, allDailyStats, cumulativeWinLossRatios] (stats) -> EventLoopFuture<[DataPoint]> in
var allDailyStats = allDailyStats
let totalWins = allDailyStats.reduce(Double(stats.totalWins)) { (total, dailyStats) -> Double in
return total + Double(dailyStats.stats.totalWins) }
let totalLosses = allDailyStats.reduce(Double(stats.totalLosses)) { (total, dailyStats) -> Double in
return total + Double(dailyStats.stats.totalLosses)
}
var cumulativeWinLossRatios = cumulativeWinLossRatios
if !(stats.totalWins == 0 && stats.totalLosses == 0) {
let date = self.createDate(day: first.day, month: first.month, year: first.year, hour: first.hour + 6, minute:first.minute) // 6 hours to make sure we pick a time that isnt on borders of us time zones
// //print ("p \(date.timeIntervalSince1970)")
let x = Double(cumulativeWinLossRatios.count)
let d = Date(timeIntervalSince1970: date.timeIntervalSince1970)
cumulativeWinLossRatios.append(DataPoint(x:x , y: (totalWins/totalLosses).truncate(places: 2), label:("\(Utilities.monthToString(month: d.month)) \(d.day)")))
}
allDailyStats.append(DailyStats(day: first.day, month: first.month, year: first.year, stats: stats, cumulativeRatio: self.getRatio(num: totalWins, den: totalLosses)))
return getRatios(remaining, allDailyStats:&allDailyStats, cumulativeWinLossRatios:&cumulativeWinLossRatios, eventLoop: eventLoop)
}
} else {
return req.eventLoop.makeSucceededFuture(cumulativeWinLossRatios)
}
}
var stats:[DailyStats] = []
var cumulativeWinLossRatios:[DataPoint] = [DataPoint]()
return getRatios(Array(previousDays)[0..<previousDays.count], allDailyStats: &stats, cumulativeWinLossRatios: &cumulativeWinLossRatios, eventLoop: req.eventLoop)
}
}
}