779 lines
30 KiB
Swift
779 lines
30 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)
|
|
|
|
}
|
|
|
|
|
|
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 getStats(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 getStatsWithMostRecentDailyRecord(sortedMatches:[Match], game:String? = nil) -> StatsWithMostRecentDailyRecord {
|
|
|
|
|
|
let startTime = Date()
|
|
//print ("MRR START \(Date().timeIntervalSince(startTime))")
|
|
|
|
let stats = getStats(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 startTime = Date()
|
|
|
|
let daysPlayed = getDaysPlayed(sortedMatches: matches)
|
|
let lastDayPlayed = daysPlayed.last
|
|
|
|
|
|
//print ("MDD days played \(Date().timeIntervalSince(startTime))")
|
|
|
|
return getStats(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)
|
|
|
|
return !isColdWar || (isColdWar && (numberOfPlayers == 0 || numberOfPlayers > 4 ))
|
|
}
|
|
|
|
|
|
|
|
private func numberOfPlayers(match:Match) -> Int {
|
|
return match.players?.components(separatedBy: ",").count ?? 0
|
|
}
|
|
|
|
private func getDaysPlayed(sortedMatches:[Match]) -> [CODDate] {
|
|
|
|
let startTime = Date()
|
|
|
|
//print ("MDP Sort \(Date().timeIntervalSince(startTime))")
|
|
|
|
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)
|
|
}
|
|
|
|
//print ("MDP to dates \(Date().timeIntervalSince(startTime))")
|
|
|
|
|
|
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.getStats(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 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 overall(req: Request) throws -> EventLoopFuture<OverallStats> {
|
|
|
|
|
|
|
|
let startTime = Date()
|
|
|
|
let statsWithHyder = statsWithPlayer(req: req, playerId: 5)
|
|
|
|
let statsWithoutHyder = statsWithoutPlayer(req: req, playerId: 5)
|
|
|
|
let hyderFuture = statsWithHyder.and(statsWithoutHyder)
|
|
|
|
let hyderStats = hyderFuture.map { (withHyder, withoutHyder) -> [Stats] in
|
|
return [withHyder, withoutHyder]
|
|
|
|
//print ("Hyder done \(Date().timeIntervalSince(startTime))")
|
|
}
|
|
|
|
|
|
let matches = Match.query(on: req.db).sort( \.$date).all()
|
|
|
|
return matches.and(hyderStats).map { (matches, hyderStats) -> (OverallStats) in
|
|
|
|
//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 mwFourPlayers:Stats?
|
|
|
|
var mapStats:[Int:Stats]?
|
|
var worstMap:Int?
|
|
var bestMap:Int?
|
|
|
|
group.enter()
|
|
queue.async {
|
|
overallStats = self.getStatsWithMostRecentDailyRecord(sortedMatches: matches)
|
|
group.leave()
|
|
//print ("all stats done \(Date().timeIntervalSince(startTime))")
|
|
}
|
|
|
|
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 )
|
|
}))
|
|
|
|
//print ("cw done \(Date().timeIntervalSince(startTime))")
|
|
|
|
group.leave()
|
|
|
|
}
|
|
|
|
group.enter()
|
|
queue.async {
|
|
mapStats = self.getMapStats(matches: matches)
|
|
//print ("maps done \(Date().timeIntervalSince(startTime))")
|
|
group.leave()
|
|
|
|
}
|
|
//
|
|
group.enter()
|
|
queue.async {
|
|
let mapStats = self.getMapStats(matches: matches)
|
|
|
|
bestMap = self.getBestMap(records: mapStats)
|
|
//print ("best done \(Date().timeIntervalSince(startTime))")
|
|
group.leave()
|
|
|
|
}
|
|
|
|
group.enter()
|
|
queue.async {
|
|
let mapStats = self.getMapStats(matches: matches)
|
|
|
|
worstMap = self.getWorstMap(records: mapStats)
|
|
//print ("worst done \(Date().timeIntervalSince(startTime))")
|
|
group.leave()
|
|
|
|
}
|
|
|
|
group.enter()
|
|
queue.async {
|
|
mwFourPlayers = self.getStatsByPlayerCount(matches: matches, playerCount: 4)
|
|
group.leave()
|
|
}
|
|
|
|
|
|
group.enter()
|
|
queue.async {
|
|
mwFivePlayers = self.getStatsByPlayerCount(matches: matches, playerCount: 5)
|
|
group.leave()
|
|
}
|
|
|
|
|
|
|
|
group.enter()
|
|
queue.async {
|
|
mwSixPlayers = self.getStatsByPlayerCount(matches: matches, playerCount: 6)
|
|
group.leave()
|
|
}
|
|
|
|
|
|
group.wait()
|
|
|
|
let dashboardItems = [
|
|
|
|
DashboardItem(title: "Total MW Games", content: "\(mwStats!.totalWins + mwStats!.totalLosses)" , title2:"", content2:""),
|
|
DashboardItem(title: "MW Overall", content: mwStats!.record, title2: "Ratio", content2: mwStats!.winLossRatio),
|
|
DashboardItem(title: "MW 6 Players ", content: mwSixPlayers!.record, title2: "Ratio", content2: mwSixPlayers!.winLossRatio),
|
|
DashboardItem(title: "MW 5 Players ", content: mwFivePlayers!.record, title2: "Ratio", content2: mwFivePlayers!.winLossRatio),
|
|
DashboardItem(title: "MW 4 Players ", content: mwFourPlayers!.record, title2: "Ratio", content2: mwFourPlayers!.winLossRatio),
|
|
DashboardItem(title: "Overall", content: overallStats!.record, title2: "Ratio", content2: overallStats!.winLossRatio),
|
|
DashboardItem(title: "Cold War Overall", content: bocwStats!.record, title2: "Ratio", content2: bocwStats!.winLossRatio),
|
|
DashboardItem(title: "With Hyder", content: hyderStats[0].record, title2: "Ratio", content2: hyderStats[0].winLossRatio),
|
|
DashboardItem(title: "No Hyder", content: hyderStats[1].record, title2: "Ratio", content2: hyderStats[1].winLossRatio),
|
|
DashboardItem(title: "Best Map", content: MapData.allMaps[bestMap!]?.name ?? "error", title2: "Ratio", content2: "\(mapStats![bestMap!]!.winLossRatio) \(mapStats![bestMap!]!.record)"),
|
|
DashboardItem(title: "Worst Map", content: MapData.allMaps[worstMap!]?.name ?? "error", title2: "Ratio", content2: "\(mapStats![worstMap!]!.winLossRatio) \(mapStats![worstMap!]!.record)"),
|
|
DashboardItem(title: "Final Kills Ruined by Adam", content: "\(matches.filter{$0.finalKillRuinedPlayerId == 6}.count + 7)", title2: "", content2: ""),
|
|
|
|
]
|
|
return OverallStats(overall: overallStats!, mwStats: mwStats!, bocwStats: bocwStats!, mostRecentRecord: "Temporarily Unavailable", statsWithHyder:hyderStats[0], statsWithoutHyder: hyderStats[1], dashboardItems:dashboardItems)
|
|
}
|
|
}
|
|
|
|
|
|
|
|
func mapRecords(req: Request) throws -> EventLoopFuture<[MapRecord]> {
|
|
|
|
return Match.query(on: req.db).all().map { (matches) -> [MapRecord] in
|
|
|
|
let mapStats = self.getMapStats(matches: matches)
|
|
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)
|
|
|
|
}
|
|
let ratio = wins / loss
|
|
|
|
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 getStatsByPlayerCount(matches:[Match], playerCount:Int) -> Stats {
|
|
|
|
return getStats(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]) -> [Int:Stats] {
|
|
var mapStats:[Int:Stats] = [Int:Stats]()
|
|
for match in matches {
|
|
|
|
if match.codGame == "mw" {
|
|
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(req: Request, playerId:Int) -> EventLoopFuture<Stats> {
|
|
return Match.query(on: req.db)
|
|
.filter(\.$players ~~ "\(playerId)")
|
|
.all().map { (matches) -> (Stats) in
|
|
return self.getStats(matches: matches)
|
|
}
|
|
|
|
}
|
|
|
|
func statsWithoutPlayer (req: Request, playerId:Int) -> EventLoopFuture<Stats> {
|
|
return Match.query(on: req.db)
|
|
.filter(\.$players !~ "\(playerId)")
|
|
.all().map { (matches) -> (Stats) in
|
|
return self.getStats(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)
|
|
}
|
|
}
|
|
}
|
|
|
|
|