import src.utils.keyboard as keyboard
import src.utils.mouse as mouse
from ...typings import Context
from .common.base import BaseTask

class ClickInClosestCreatureTask(BaseTask):
    def __init__(self):
        super().__init__()
        self.name = 'clickInClosestCreature'
        self.delayOfTimeout = 5

    def shouldIgnore(self, context: Context) -> bool:
        attackBox = getattr(self.parentTask, 'parentTask', None)
        trappedWalk = getattr(attackBox, 'parentTask', None)
        if (getattr(attackBox, 'name', None) == 'attackMonstersBox' and
                getattr(trappedWalk, 'isTrapped', False)):
            return False
        return context['ng_cave']['targetCreature'] is not None

    def do(self, context: Context) -> Context:
        closestCreature = context['ng_cave']['closestCreature']
        attackBox = getattr(self.parentTask, 'parentTask', None)
        trappedWalk = getattr(attackBox, 'parentTask', None)
        isBlockingCreature = (
            getattr(attackBox, 'name', None) == 'attackMonstersBox' and
            getattr(trappedWalk, 'isTrapped', False)
        )
        blocker = getattr(trappedWalk, 'blockingCreature', None)
        if blocker is not None:
            closestCreature = blocker
        if (closestCreature is None and isBlockingCreature and
                context['gameWindow']['monsters']):
            closestCreature = context['gameWindow']['monsters'][0]

        if isBlockingCreature and closestCreature is not None:
            windowCoordinate = closestCreature.get('windowCoordinate')
            if windowCoordinate is not None:
                mouse.attackClick(windowCoordinate)
            elif context['ng_cave']['isAttackingSomeCreature'] == False:
                keyboard.press('space')
            return context

        if context['ng_cave']['isAttackingSomeCreature'] == False:
            # Immer praezise auf das per Score gewaehlte Ziel klicken;
            # Space (Client-Zielwahl) nur, wenn keine Fensterposition
            # bekannt ist — und gar nicht, wenn ignorierbare Kreaturen
            # auf dem Screen sind, die der Client sonst treffen koennte.
            if closestCreature and closestCreature.get('windowCoordinate'):
                mouse.attackClick(closestCreature['windowCoordinate'])
            elif (closestCreature is not None
                    or not context['ng_targeting']['hasIgnorableCreatures']):
                keyboard.press('space')

        return context

    def did(self, context: Context) -> bool:
        return context['ng_cave']['isAttackingSomeCreature']
