from collections import OrderedDict

import tcod.event

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


def run(scene: GameScene):
    brains = [b for b in scene.cm.get(Brain) if b.intention is Intention.EQUIP_SLOT]
    for brain in brains:
        entity = brain.entity
        menu_actions = OrderedDict()
        equip_action = MenuAction('e', 'equip', lambda obj: set_intention(scene, entity, obj, Intention.EQUIP_ITEM))
        menu_actions[tcod.event.K_e] = equip_action
        inventory_scene = ListMenuScene(
            "Equip which?",
            get_inventory_query(scene, entity),
            row_builder=row_builder,
            default_action=equip_action,
            menu_actions=menu_actions,
            id_extractor=lambda e: e.id,
            parent_scene=scene,
            close_after_action=True
        )
        scene.controller.push_scene(inventory_scene)
        retract_intention(scene, entity)


def get_inventory_query(scene, entity):
    """Return a query that resolves to entity's inventory."""

    def query():
        return [
            scene.cm.get_one(Entity, g.entity)
            for g in scene.cm.get(Getable) if (
                g.held_by == entity
            )
        ]

    return query


def row_builder(entity):
    return [entity.name]
