An amazing project that generates micro reports from tournament results
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.9 KiB

//
// Importer.swift
// TournamentStats
//
// Created by Laurent Morvillier on 02/06/2019.
// Copyright © 2019 Stax River. All rights reserved.
//
import Foundation
import RealmSwift
import Realm
enum Columns : CaseIterable {
case rank
case player
case earnings
case poy
case city
case state
case country
}
class Importer {
static func start() {
let realm = try! Realm()
let tournaments = realm.objects(Tournament.self).sorted(byKeyPath: "number", ascending: false)
print("Tournaments count = \(tournaments.count)")
for tournament in tournaments {
try! realm.write {
let resourceName = "event\(tournament.number)"
let path: String? = Bundle.main.path(forResource: resourceName, ofType: "")
if let path = path {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
Importer.createResults(realm: realm, tournament: tournament, data: data)
} catch {
print(error)
}
} else {
print("could not find path for event \(tournament.number)")
}
}
}
}
static func createResults(realm: Realm, tournament: Tournament, data: String) {
// cleanup raw data
let rawRows = data.split(separator: "\n")
var rows = rawRows.map { String($0) }
rows = rows.filter { !$0.isEmpty }
let columns = tournament.rows
let numberOfColumns = columns.count
let formatter = Formatter.importData
var result: Result?
var player: Player?
var playerName: String = ""
var city: String = ""
var state: String = ""
var country: String = ""
for i in 0..<rows.count {
let row: String = rows[i]
let index = i % numberOfColumns
let currentColumn = columns[index]
switch currentColumn {
case .rank:
let newResult = realm.create(Result.self)
tournament.results.append(newResult)
newResult.rank = formatter.number(from: row)?.intValue ?? 0
result = newResult
case .player:
var rowCopy = row
var previousChar: Character?, currentChar: Character = row.first!
while (!(currentChar.isUppercase && previousChar != nil && !previousChar!.isWhitespace)) {
previousChar = currentChar
rowCopy = String(rowCopy.dropFirst())
if let char = rowCopy.first {
currentChar = char
} else {
playerName = row
break
}
}
playerName = rowCopy
case .earnings:
let parsed = String(row.dropFirst())
let earnings = formatter.number(from: parsed)?.doubleValue
result?.earnings = earnings!
case .poy:
let poy = formatter.number(from: row)?.doubleValue
result?.poyPoints = poy!
case .city:
city = row
case .state:
state = row
case .country:
country = row
let notable: Bool = NotablePlayers.all.contains(playerName)
player = realm.getOrCreatePlayer(name: playerName, city: city, state: state, country: country, notable: notable)
result?.player = player
}
}
}
}