from src.gameplay.typings import Context
from src.repositories.gameWindow.core import getSlotFromCoordinate
import src.repositories.gameWindow.slot as gameWindowSlot
from src.repositories.gameWindow.typings import Creature
import src.utils.keyboard as utilsKeyboard
from ...typings import Context
from .common.base import BaseTask

ATTEMPT_LIMIT = 2


class CollectDeadCorpseTask(BaseTask):
    """Lootet gezielt den Leichen-Slot samt Nachbarn (nicht blind 3x3).

    Die Leiche wird nur aus der Liste genommen, wenn sie in Reichweite
    war oder ATTEMPT_LIMIT Versuche verbraucht sind — der Rest der
    Warteschlange bleibt erhalten.
    """

    def __init__(self, creature: Creature):
        super().__init__()
        self.name = 'collectDeadCorpse'
        self.creature = creature
        self.wasReachable = False

    def do(self, context: Context) -> Context:
        slot = getSlotFromCoordinate(
            context['ng_radar']['coordinate'], self.creature['coordinate'])
        if slot is None:
            return context
        self.wasReachable = True
        neighbors = [
            (x, y)
            for x in range(max(slot[0] - 1, 0), min(slot[0] + 2, 15))
            for y in range(max(slot[1] - 1, 0), min(slot[1] + 2, 11))
        ]
        utilsKeyboard.keyDown('shift')
        try:
            for neighbor in neighbors:
                gameWindowSlot.rightClickSlot(
                    [neighbor[0], neighbor[1]],
                    context['gameWindow']['coordinate'])
        finally:
            utilsKeyboard.keyUp('shift')
        return context

    def onComplete(self, context: Context) -> Context:
        self.creature['lootAttempts'] = \
            self.creature.get('lootAttempts', 0) + 1
        if self.wasReachable or \
                self.creature['lootAttempts'] >= ATTEMPT_LIMIT:
            context['loot']['corpsesToLoot'] = [
                corpse for corpse in context['loot']['corpsesToLoot']
                if corpse is not self.creature
            ]
        return context
