using System.Globalization;
using System.Text.Json.Nodes;
namespace Pokerfreak.Cockpit.Kern;
///
/// Welche Turniere der Laeufer anmeldet (wie cockpit/src/turnierplan.rs, Turnierplan.swift,
/// betrieb/turnierplan.py): ein Buy-in-Band, die CoinPoker-Kategorie (der Typ), ein freies
/// Namens-Teilwort, nur laufende (Late-Reg) und ein Startfenster in Minuten. Im Spielplan steht er
/// als `turnier`-Objekt - nur, wenn der Owner ueberhaupt etwas eingeschraenkt hat.
///
public sealed class Turnierplan
{
/// Der Typ-Filter: Anzeige und Kategorie (null = alle).
public static readonly (string Name, string? Kategorie)[] Typen =
{
("Alle", null), ("Daily", "Daily"), ("Satellite", "Satellite"), ("PGT", "PGT"), ("Freerolls", "Freeroll"), ("VIP", "VIP"),
};
public double? BuyinMin, BuyinMax;
public string? Name, Kategorie;
public bool NurLaufend = true;
public long? FensterMin;
private static string? Text(JsonObject o, string k) =>
o[k] is JsonValue v && v.TryGetValue(out var s) && s.Trim().Length > 0 ? s.Trim() : null;
/// Nachsichtig aus `spielplan.turnier`; fehlt es, die Vorgabe.
public static Turnierplan Aus(JsonObject? o)
{
var p = new Turnierplan();
if (o == null) return p;
p.BuyinMin = o.Zahl("buyin_min");
p.BuyinMax = o.Zahl("buyin_max");
p.Name = Text(o, "name");
p.Kategorie = Text(o, "kategorie");
p.NurLaufend = o["nur_laufend"] is JsonValue nl && nl.TryGetValue(out var b) ? b : true;
p.FensterMin = o.Zahl("fenster_min") is double f && f > 0 ? (long)f : null;
return p;
}
public bool Gesetzt => BuyinMin != null || BuyinMax != null || Name != null || Kategorie != null || FensterMin != null || !NurLaufend;
/// Fuer `Spielplan.turnier`: null, solange nichts gesetzt ist.
public JsonObject? Daten()
{
if (!Gesetzt) return null;
var d = new JsonObject { ["nur_laufend"] = NurLaufend };
if (BuyinMin is double a) d["buyin_min"] = a;
if (BuyinMax is double b) d["buyin_max"] = b;
if (Name != null) d["name"] = Name;
if (Kategorie != null) d["kategorie"] = Kategorie;
if (FensterMin is long m) d["fenster_min"] = m;
return d;
}
public int TypIndex => Math.Max(0, Array.FindIndex(Typen, t => t.Kategorie == Kategorie));
public void TypSetzen(int i) => Kategorie = i >= 0 && i < Typen.Length ? Typen[i].Kategorie : null;
/// Ein Buy-in aus dem Feld: Komma wie Punkt, leer oder <= 0 heisst offenes Ende.
public static double? BetragLesen(string roh) =>
double.TryParse(roh.Trim().Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var x) && x > 0 && double.IsFinite(x) ? x : null;
/// Minuten aus dem Feld: leer oder <= 0 heisst kein Zeitfenster.
public static long? MinutenLesen(string roh) => long.TryParse(roh.Trim(), out var x) && x > 0 ? x : null;
/// Fuers Feld ohne Tausenderpunkt: "2,5", "10".
public static string BetragText(double? x) =>
x is double v ? v.ToString("0.##", CultureInfo.InvariantCulture).Replace('.', ',') : "";
}