from commands.command import Command


class MoveCommand(Command):
    DIRECTION_TO_DELTA = {
        "W": (0, -1),
        "A": (-1, 0),
        "S": (0, 1),
        "D": (1, 0),
    }

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

    def execute(self):
        if self.direction not in self.DIRECTION_TO_DELTA:
            return False

        dx, dy = self.DIRECTION_TO_DELTA[self.direction]
        current = self.player.currentCell
        new_cell = self.maze.getCell(current.x + dx, current.y + dy)

        if new_cell is None or not new_cell.isPassable():
            return False

        self.previousCell = current
        self.player.setCell(new_cell)
        return True

    def undo(self):
        if self.previousCell is None:
            return False
        self.player.setCell(self.previousCell)
        return True
