from src.gameplay.core.tasks.orchestrator import TasksOrchestrator
from src.gameplay.core.tasks.useHotkey import UseHotkeyTask
from src.gameplay.core.tasks.useSlotItem import UseSlotItemTask
from src.gameplay.reaction import ReactionGate
from ...typings import Context
from ..utils.potions import matchHpHealing


tasksOrchestrator = TasksOrchestrator()
potionGate = ReactionGate()


def usePotionTask(potion, smartHotkeys=False):
    """Slot-Klick im Smart-Modus mit bekanntem Slot, sonst Hotkey."""
    if smartHotkeys and potion.get('slot'):
        return UseSlotItemTask(
            potion['slot'], fallbackHotkey=potion.get('hotkey'),
            delayAfterComplete=1)
    return UseHotkeyTask(potion['hotkey'], delayAfterComplete=1)


# TODO: add unit tests
def healingByPotions(context: Context):
    currentTask = tasksOrchestrator.getCurrentTask(context)
    if currentTask is not None:
        if currentTask.status == 'completed':
            tasksOrchestrator.reset()
        else:
            tasksOrchestrator.do(context)
            return
    potion = context['healing']['potions']['firstHealthPotion']
    if potion['enabled']:
        urgent = (context['ng_statusBar'].get('hpPercentage') or 100) < 50
        if potionGate.ready(matchHpHealing(potion, context['ng_statusBar']), urgent=urgent):
            tasksOrchestrator.setRootTask(context, usePotionTask(
                potion, context.get('ng_actionBar', {}).get('smartHotkeys', False)))
            return
