# original Copyright Ruben Decrop
# modifications by Chessdevil Consulting BVBA

import logging
log = logging.getLogger(__name__)

def pairingsfromswar(swarjson):
    """
    get the pairings from the swarjson structure
    :param swarjson:
    :return:
    """
    (standings, pairings, bye, absences) = processswarjson(swarjson)
    skeys = sorted(pairings.keys())
    p = [pairings[k] for k in skeys]
    if bye:
        p.append(bye)
    p.extend(absences)
    return p

def standingsfromswar(swarjson):
    """
    get the pairings from the swarjson structure
    :param swarjson:
    :return:
    """
    (standings, pairings, bye, absences) = processswarjson(swarjson)
    skeys = sorted(standings.keys())
    s = [standings[k] for k in skeys]
    return s

def processswarjson(swarjson):
    """
    process the jsswarjson file calculating players and pairings
    standings, pairings, bye are dicts
    absences a list
    :param swarjson:
    :return: (standings, pairings, bye, absences)
    """
    pairings = {}
    standings = {}
    absences = []
    bye = None
    swar = swarjson.get('Swar')
    if not swar:
        log.debug('no swar file')
        return (standings, pairings, bye, absences)
    players = swar.get('Player')
    if not players:
        log.debug('no swar file')
        return (standings, pairings, bye, absences)
    for p in players:
        six = p.get('Ranking') - 1
        pl = {
            "name": p.get('Name'),
            "playerindex": p.get("Ni"),
            "points": float(p.get("Points")),
            "gender": "M" if p.get("Sex") else  'F' ,
            "country": p.get("Country"),
            "id_national": str(p.get("NationalId")),
            "id_fide": str(p.get("FideId")),
            "id_club": str(p.get("ClubNumber")),
            "clubname": p.get("ClubName"),
            "natrating": p.get("NationalElo", 0),
            "fiderating": p.get("FideElo", 0),
            "titel": p.get("Titel"),
            "ngames": p.get("NbOfParts"),
            "games": [],
            "bye": None,
            "absences": [],
        }
        pl["rating"] = max(pl["natrating"], pl["fiderating"])
        ra = p.get("RoundArray")
        for ix, g in enumerate(ra):
            if len(ra) == ix + 1:
                standings[six] = pl
            round = g.get("RoundNr")
            if g.get("Tabel") == "Absent":
                pl["absences"].append({"round": int(round) -1})
                if len(ra) == ix + 1:
                    absences.append({
                        "white": pl["name"],
                        "result": "--",
                    })
                continue
            if g.get("Tabel") == "BYE":
                pl["bye"] = {"round": int(round) -1}
                if len(ra) == ix +1:
                    bye = {
                        "white": pl["name"],
                        "result": "Bye",
                    }
                continue
            lastgame = {
                "table": int(g.get("Tabel")) - 1,
                "opponentIndex": g.get("OpponentNi"),
                "opponentName": g.get("OpponentName"),
                "result": g.get("Result").upper(),
                "color": "B" if g.get("Color") == "Black" else 'W',
                "float": g.get("Float"),
                "round": int(round)-1,
            }
            pl["games"].append(lastgame)
            if len(ra) == ix + 1:
                pix = lastgame["table"]
                pairings.setdefault(pix, {})
                if lastgame["color"] == "W":
                    lg = {
                        "white": pl["name"],
                        "black": lastgame["opponentName"],
                    }
                    if lastgame["result"] == "1":
                        lg["result"] = "1-0"
                    elif lastgame["result"] == "½":
                        lg["result"] = "½-½"
                    elif lastgame["result"] == "0":
                        lg["result"] = "0-1"
                    elif lastgame["result"] == "1FF":
                        lg["result"] = "1-0 FF"
                    elif lastgame["result"] == "0FF":
                        lg["result"] = "0-1 FF"
                    else:
                        lg["result"] = "???"
                    pairings[pix] = lg
    return (standings, pairings, bye, absences)
