

from collections import OrderedDict

import tcod.event

from components import Entity, PaperDoll, Brain
from components.enums import Intention
from engine import GameScene
from scenes.list_menu_scene import MenuAction, ListMenuScene
from systems.utilities import set_intention, retract_intention


def run(scene: GameScene):
    handle_show_equip_screen(scene)


def handle_show_equip_screen(scene: GameScene):
    brains = [b for b in scene.cm.get(Brain) if b.intention is Intention.SHOW_EQUIP_SCREEN]
    for brain in brains:
        entity = brain.entity
        menu_actions = OrderedDict()
        equip_action = MenuAction('e', 'equip', lambda slot: set_intention(scene, entity, slot, Intention.EQUIP_SLOT))
        menu_actions[tcod.event.K_e] = equip_action
        equipment_scene = ListMenuScene(
            "Equipment",
            get_slots_query(scene, entity),
            row_builder=row_builder,
            default_action=equip_action,
            menu_actions=menu_actions,
            id_extractor=lambda e: e[1],
            parent_scene=scene
        )
        scene.controller.push_scene(equipment_scene)
        retract_intention(scene, entity)


def get_slots_query(scene: GameScene, entity: int):
    """Return a query that resolves to entity's equipment slots and their equipped items."""

    def query():

        paper_doll: PaperDoll = scene.cm.get_one(PaperDoll, entity)
        equipment = paper_doll.get_equipment()

        return [
            (k, scene.cm.get_one(Entity, v))
            for k, v in equipment.items()
        ]
    return query


def row_builder(entity):
    part_name = entity[0]
    equipped = entity[1].name if entity[1] else ''
    return [part_name, equipped]
