from command.command import Command


class MoveCommand(Command):

    def __init__(
        self,
        player,
        maze,
        direction
    ):
        self.player = player
        self.maze = maze
        self.direction = direction
        self.previous = None

    def _targetCell(self):

        offsets = {
            "W": (0, -1),
            "S": (0, 1),
            "A": (-1, 0),
            "D": (1, 0)
        }

        dx, dy = offsets.get(
            self.direction.upper(),
            (0, 0)
        )

        x, y = self.player.getPosition()

        return self.maze.getCell(
            x + dx,
            y + dy
        )

    def execute(self):

        destination = self._targetCell()

        if destination is None:
            return False

        if not destination.isPassable():
            return False

        self.previous = self.player.current

        self.player.place(
            destination
        )

        return True

    def undo(self):

        if self.previous is None:
            return False

        self.player.place(
            self.previous
        )

        return True