Files
lichtkasten/Sources/LichtkastenCore/Metadata/CodeLibrary.swift
T
Lichtkasten DevandClaude Opus 5.5 d559a4f182 Kürzel-Änderung gilt auch für Trainer- und Staff-Codes
Codes ohne Rückennummer (z. B. „htr“ Trainer, „h-co“ Co-Trainer) werden beim Umstellen h → hs mit
umbenannt (hstr, hs-co) und auch beim Nachladen der TXT umgestellt; Codes, die schon mit dem neuen
Kürzel beginnen, bleiben unverändert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
2026-11-17 19:51:01 +00:00

317 lines
17 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
/// One code line: "w10 ⇥ Svenja Huth (VfL Wolfsburg, 10) ⇥ …"
public struct CodeEntry: Codable, Hashable, Identifiable, Sendable {
public var id = UUID()
public var code: String
public var columns: [String]
public init(code: String, columns: [String]) { self.code = code; self.columns = columns }
enum CodingKeys: String, CodingKey { case code, columns }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
code = try c.decode(String.self, forKey: .code)
columns = try c.decodeIfPresent([String].self, forKey: .columns) ?? []
}
}
/// A team (or any group of codes) – like one enabled file in PM's Code Replacement list,
/// but stored in the app so players can be added by hand and merged from new TXT files.
public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
public var id = UUID()
public var name: String
/// League / group the team is sorted under ("1. Bundesliga", "2. Bundesliga" …) – empty = no league.
/// Imported from the folder the TXT lies in.
public var league: String = ""
public var enabled = true
public var entries: [CodeEntry] = []
/// TXT file the team was imported from (for "Reload" / auto reload).
public var sourcePath: String?
public var sourceModified: Date?
/// Own short codes instead of the ones in the TXT, e.g. ["h": "hs"] – applied to every (re)import,
/// so reloading the TXT does not bring the old codes back.
public var prefixMap: [String: String] = [:]
public init(name: String, league: String = "", entries: [CodeEntry] = [], sourcePath: String? = nil) {
self.name = name; self.league = league; self.entries = entries; self.sourcePath = sourcePath
}
enum CodingKeys: String, CodingKey { case id, name, league, enabled, entries, sourcePath, sourceModified, prefixMap }
/// Tolerant: a missing/new field must never cost the players.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = (try? c.decode(UUID.self, forKey: .id)) ?? UUID()
name = (try? c.decode(String.self, forKey: .name)) ?? "Team"
enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? true
entries = (try? c.decode([CodeEntry].self, forKey: .entries)) ?? []
sourcePath = try? c.decode(String.self, forKey: .sourcePath)
sourceModified = try? c.decode(Date.self, forKey: .sourceModified)
prefixMap = (try? c.decode([String: String].self, forKey: .prefixMap)) ?? [:]
// teams from before leagues existed: sorted under the folder their TXT lies in
league = (try? c.decode(String.self, forKey: .league)) ?? sourcePath.map(CodeSet.league(forFile:)) ?? ""
}
/// League of a TXT = name of its folder ("…/Codes/1. Bundesliga/VfL Wolfsburg.txt" → "1. Bundesliga").
public static func league(forFile path: String) -> String {
URL(fileURLWithPath: path).deletingLastPathComponent().lastPathComponent
}
/// Letters + number of a code ("hs10" → ("hs", "10")), nil for codes of another shape.
static func split(_ code: String) -> (prefix: String, rest: String)? {
let p = String(code.prefix { !$0.isNumber })
let rest = String(code.dropFirst(p.count))
guard !p.isEmpty, let first = rest.first, first.isNumber,
rest.split(separator: "#", maxSplits: 1).first?.allSatisfy(\.isNumber) == true else { return nil }
return (p, rest)
}
/// The code as this team uses it (own short code applied) – players and trainer/staff codes alike.
public func mapped(_ code: String) -> String {
// longest matching old prefix wins ("hs" before "h")
for (from, to) in prefixMap.sorted(by: { $0.key.count > $1.key.count }) {
if let r = CodeSet.renamed(code, from: from, to: to) { return r }
}
return code
}
/// One code with the short code changed, nil if it does not use `from`:
/// players "h10" → "hs10" (letters must be exactly the prefix), and codes without a number –
/// trainer "htr", "h-co" … → "hstr", "hs-co" (start with the prefix).
static func renamed(_ code: String, from: String, to: String) -> String? {
if let (p, rest) = split(code) { return p.lowercased() == from ? to + rest : nil }
let lc = code.lowercased()
guard lc.hasPrefix(from), lc.count > from.count else { return nil }
if to.hasPrefix(from) && lc.hasPrefix(to) { return nil } // already has the new prefix
return to + String(code.dropFirst(from.count))
}
/// Short code of the team as it is now ("h" for h10, h7 …).
public var currentPrefix: String { JerseyLogic.detectPrefix(codes: entries.map(\.code)) }
/// Changes the team's short code: h10 → hs10, h7 → hs7 … and remembers it for later TXT reloads.
/// Returns the number of renamed codes.
@discardableResult
public mutating func renamePrefix(from old: String, to new: String) -> Int {
let from = old.lowercased(), to = new.trimmingCharacters(in: .whitespaces).lowercased()
guard !from.isEmpty, !to.isEmpty, from != to, to.allSatisfy(\.isLetter) else { return 0 }
let existing = Set(entries.map { $0.code.lowercased() })
var n = 0
for i in entries.indices {
guard let renamed = CodeSet.renamed(entries[i].code, from: from, to: to) else { continue }
if existing.contains(renamed.lowercased()) { continue } // never two players on one code
entries[i].code = renamed
n += 1
}
// codes from the TXT (original prefix) → new prefix; chains h → hs → s stay one step
for (k, v) in prefixMap where v == from { prefixMap[k] = to }
if prefixMap[from] == nil { prefixMap[from] = to }
prefixMap = prefixMap.filter { $0.key != $0.value }
return n
}
/// Adds only codes that are not in the team yet (existing players stay untouched).
@discardableResult
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
var known = Set(entries.map { $0.code.lowercased() })
var added = 0, existing = 0
for var e in new {
e.code = mapped(e.code)
let k = e.code.lowercased()
if known.contains(k) { existing += 1; continue }
entries.append(e)
known.insert(k)
added += 1
}
return (added, existing)
}
}
public struct CodeLibrary: Codable, Sendable {
public var sets: [CodeSet] = []
public var delimiter: String = "\\"
public var defaultReplacement = ""
public var bareCodes = true
public var autoReload = false
/// Folders imported as a whole ("Codes" with "1. Bundesliga", "Testspiele" …) – new TXT files and
/// league folders inside are picked up automatically.
public var rootFolders: [String] = []
public init() {}
enum CodingKeys: String, CodingKey { case sets, delimiter, defaultReplacement, bareCodes, autoReload, rootFolders }
/// Tolerant decoding (see CodeSet).
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
sets = (try? c.decode([CodeSet].self, forKey: .sets)) ?? []
delimiter = (try? c.decode(String.self, forKey: .delimiter)) ?? "\\"
defaultReplacement = (try? c.decode(String.self, forKey: .defaultReplacement)) ?? ""
bareCodes = (try? c.decode(Bool.self, forKey: .bareCodes)) ?? true
autoReload = (try? c.decode(Bool.self, forKey: .autoReload)) ?? false
rootFolders = (try? c.decode([String].self, forKey: .rootFolders)) ?? []
}
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
public var replacements: CodeReplacements {
var table: [String: [String]] = [:]
// same order as shown (league by league) – the upper team wins on duplicate codes
for set in grouped.flatMap(\.sets) where set.enabled {
for e in set.entries where table[e.code.lowercased()] == nil { table[e.code.lowercased()] = e.columns }
}
var r = CodeReplacements(table: table)
r.delimiter = delimiter.first ?? "\\"
r.defaultReplacement = defaultReplacement
r.bareCodes = bareCodes
return r
}
/// Parses PM's tab-delimited code file (code ⇥ replacement ⇥ more columns). '#' lines are comments.
public static func parse(_ text: String) -> [CodeEntry] {
var out: [CodeEntry] = []
for line in text.components(separatedBy: .newlines) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
let cols = line.components(separatedBy: "\t")
guard cols.count >= 2 else { continue }
let code = cols[0].trimmingCharacters(in: .whitespaces)
guard !code.isEmpty else { continue }
out.append(CodeEntry(code: code, columns: cols.dropFirst().map { $0.trimmingCharacters(in: .whitespaces) }))
}
return out
}
/// Reads a code file in UTF-8, UTF-16 (PM sometimes saves that), Windows-1252 or Mac Roman.
public static func readText(_ url: URL) throws -> String {
let data = try Data(contentsOf: url)
// UTF-16 only with a byte order mark – without one, almost any Latin-1 file "decodes" as UTF-16 garbage
if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]), let s = String(data: data, encoding: .utf16) {
return s
}
for enc in [String.Encoding.utf8, .windowsCP1252, .macOSRoman] {
if let s = String(data: data, encoding: enc) { return s }
}
return String(decoding: data, as: UTF8.self)
}
/// Leagues in list order (first appearance), teams without league last.
public var leagues: [String] {
var seen: [String] = []
for s in sets where !seen.contains(s.league) { seen.append(s.league) }
return seen.filter { !$0.isEmpty } + (seen.contains("") ? [""] : [])
}
/// Teams grouped by league, in list order (for pickers and the code window).
public var grouped: [(league: String, sets: [CodeSet])] {
leagues.map { l in (l, sets.filter { $0.league == l }) }
}
/// Imports a folder of TXT files: every TXT becomes a team, its league is the folder it lies in –
/// choose the parent folder ("Codes" with "1. Bundesliga", "2. Bundesliga" …) or one league folder.
@discardableResult
public mutating func importFolder(_ folder: URL) throws -> [(team: String, added: Int, existing: Int)] {
let fm = FileManager.default
guard let e = fm.enumerator(at: folder, includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles, .skipsPackageDescendants], errorHandler: { _, _ in true }) else { return [] }
let txts = e.compactMap { $0 as? URL }.filter { $0.pathExtension.lowercased() == "txt" }
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
let path = folder.standardizedFileURL.path
if !rootFolders.contains(path) { rootFolders.append(path) }
return try txts.map { try importFile($0) }
}
/// Folders to watch for new code files: the imported roots, plus – for libraries from before – the
/// common parent of league folders ("Codes/1. Bundesliga/…" + "Codes/2. Bundesliga/…" → "Codes").
public var effectiveRoots: [String] {
var roots = rootFolders
var leaguesPerParent: [String: Set<String>] = [:]
for s in sets {
guard let p = s.sourcePath else { continue }
let league = URL(fileURLWithPath: p).deletingLastPathComponent()
leaguesPerParent[league.deletingLastPathComponent().path, default: []].insert(league.path)
}
for (parent, leagues) in leaguesPerParent where leagues.count >= 2 && !roots.contains(parent) { roots.append(parent) }
return roots.filter { FileManager.default.fileExists(atPath: $0) }
}
/// New TXT files / league folders in the watched folders become teams (e.g. a new "Testspiele" folder).
/// Known files are left to reloadAll (new players only). Returns the new teams.
@discardableResult
public mutating func importNewFiles() -> [String] {
let known = Set(sets.compactMap { $0.sourcePath.map { URL(fileURLWithPath: $0).standardizedFileURL.path } })
var added: [String] = []
for root in effectiveRoots {
guard let e = FileManager.default.enumerator(at: URL(fileURLWithPath: root), includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles, .skipsPackageDescendants],
errorHandler: { _, _ in true }) else { continue }
let txts = e.compactMap { $0 as? URL }.filter { $0.pathExtension.lowercased() == "txt" }
.filter { !known.contains($0.standardizedFileURL.path) }
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
for t in txts { if let r = try? importFile(t) { added.append(r.team) } }
}
return added
}
/// Imports a TXT: merges into the team with the same source file (or name), otherwise creates a new team.
/// The league comes from the folder of the file (unless given).
@discardableResult
public mutating func importFile(_ url: URL, into setID: UUID? = nil, league: String? = nil) throws -> (team: String, added: Int, existing: Int) {
let entries = CodeLibrary.parse(try CodeLibrary.readText(url))
let mod = (try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]) as? Date
let name = url.deletingPathExtension().lastPathComponent.replacingOccurrences(of: "_", with: " ")
let idx = setID.flatMap { id in sets.firstIndex { $0.id == id } }
?? sets.firstIndex { $0.sourcePath == url.path }
?? sets.firstIndex { $0.name.caseInsensitiveCompare(name) == .orderedSame
&& (league ?? CodeSet.league(forFile: url.path)).caseInsensitiveCompare($0.league) == .orderedSame }
if let i = idx {
let r = sets[i].merge(entries)
if sets[i].sourcePath == nil || setID == nil { sets[i].sourcePath = url.path }
sets[i].sourceModified = mod
if sets[i].league.isEmpty { sets[i].league = league ?? CodeSet.league(forFile: url.path) }
return (sets[i].name, r.added, r.existing)
}
var set = CodeSet(name: name, league: league ?? CodeSet.league(forFile: url.path), sourcePath: url.path)
let r = set.merge(entries)
set.sourceModified = mod
sets.append(set)
return (name, r.added, r.existing)
}
/// Re-reads all source files (PM "Reload All" / auto reload) – only new codes are added.
@discardableResult
public mutating func reloadAll(onlyChanged: Bool = false) -> Int {
var added = 0
for i in sets.indices {
guard let path = sets[i].sourcePath, FileManager.default.fileExists(atPath: path) else { continue }
let mod = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate]) as? Date
if onlyChanged, let m = mod, let known = sets[i].sourceModified, m <= known { continue }
guard let text = try? CodeLibrary.readText(URL(fileURLWithPath: path)) else { continue }
added += sets[i].merge(CodeLibrary.parse(text)).added
sets[i].sourceModified = mod
}
return added
}
/// Moves a team within its league (code window drag & drop) – order = priority on duplicate codes.
public mutating func move(inLeague league: String, from source: IndexSet, to destination: Int) {
let positions = sets.indices.filter { sets[$0].league == league }
let group = positions.map { sets[$0] }
// same semantics as SwiftUI's move(fromOffsets:toOffset:) – Core stays Foundation-only
let moving = source.sorted().map { group[$0] }
var rest = group.enumerated().filter { !source.contains($0.offset) }.map(\.element)
rest.insert(contentsOf: moving, at: max(0, min(rest.count, destination - source.filter { $0 < destination }.count)))
for (p, s) in zip(positions, rest) { sets[p] = s }
}
/// Migration from the old flat code table.
public static func migrate(_ old: CodeReplacements) -> CodeLibrary {
var lib = CodeLibrary()
lib.delimiter = String(old.delimiter)
if !old.table.isEmpty {
lib.sets = [CodeSet(name: "Importiert", entries: old.table.sorted { $0.key < $1.key }.map { CodeEntry(code: $0.key, columns: $0.value) })]
}
return lib
}
}