# wcs/games/answer_nav.py
"""Pohyb šipkami mezi odpověďmi A-D a nápovědami Milionáře, když některá z nich je vypnutá.

XML má pevnou navigaci (A-B nad C-D, nápovědy nad nimi) a Kodi na vypnutý ovladač nepřeskočí: po 50:50 zbudou třeba
jen B a C, které jsou v mřížce úhlopříčně, a šipky z B vedou na A a D, takže hráč na C nedojde. `reroute` vrátí pro
takovou šipku nejbližší povolený ovladač v jejím směru; kde XML vede na povolený ovladač (nebo nikam), vrátí None
a pohyb nechá Kodi.
"""
from wcs.games.designs import ANSWER_IDS

ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4

_ANSWER_POSITIONS = {control: (index // 2, index % 2) for index, control in enumerate(ANSWER_IDS)}


def reroute(focus_id, action_id, life_ids, is_enabled):
    """The control to focus instead of the disabled one the layout leads to, or None to leave the move to Kodi.

    life_ids: the three lifeline controls (50:50, tip, audience) of the design; is_enabled(control_id) -> bool."""
    a, b, c, d = ANSWER_IDS
    l1, l2, l3 = life_ids
    layout = {                      # what the XML of both designs does for an arrow
        a: {ACTION_MOVE_UP: l1, ACTION_MOVE_DOWN: c, ACTION_MOVE_RIGHT: b},
        b: {ACTION_MOVE_UP: l2, ACTION_MOVE_DOWN: d, ACTION_MOVE_LEFT: a},
        c: {ACTION_MOVE_UP: a, ACTION_MOVE_RIGHT: d},
        d: {ACTION_MOVE_UP: b, ACTION_MOVE_LEFT: c},
        l1: {ACTION_MOVE_DOWN: a, ACTION_MOVE_RIGHT: l2},
        l2: {ACTION_MOVE_DOWN: b, ACTION_MOVE_LEFT: l1, ACTION_MOVE_RIGHT: l3},
        l3: {ACTION_MOVE_DOWN: b, ACTION_MOVE_LEFT: l2},
    }
    target = layout.get(focus_id, {}).get(action_id)
    if target is None or is_enabled(target):
        return None
    positions = dict(_ANSWER_POSITIONS)
    positions.update({l1: (-1, 0.0), l2: (-1, 0.5), l3: (-1, 1.0)})
    row, col = positions[focus_id]
    horizontal = action_id in (ACTION_MOVE_LEFT, ACTION_MOVE_RIGHT)
    best = None
    for control, (r, k) in positions.items():
        if control == focus_id or not is_enabled(control):
            continue
        if horizontal and (focus_id in _ANSWER_POSITIONS) != (control in _ANSWER_POSITIONS):
            continue                # left / right never leaves the answers for the lifelines, or the other way round
        ahead = {ACTION_MOVE_LEFT: k < col, ACTION_MOVE_RIGHT: k > col,
                 ACTION_MOVE_UP: r < row, ACTION_MOVE_DOWN: r > row}[action_id]
        if not ahead:
            continue
        distance = (r - row) ** 2 + (k - col) ** 2
        if best is None or distance < best[0]:
            best = (distance, control)
    return best[1] if best else None
