from .actions import parse_actions, parse_commands


class Tile(object):

    def __init__(self, name, front=None, back=None,
                 front_commands=None, back_commands=None):
        self.name = name
        self.front = parse_actions(front)
        self.back = parse_actions(back)
        self.front_commands = parse_commands(front_commands)
        self.back_commands = parse_commands(back_commands)

    def __str__(self):
        return self.name

    def __repr__(self):
        return '<Tile {}>'.format(self.name.upper())

    def action(self, x, y, side):
        actions = self.front if side == 'front' else self.back
        return actions.get((x, y))

    def command(self, x, y, side):
        commands = self.front_commands if side == 'front' else self.back_commands
        return commands.get((x, y))

    def on_board(self, color):
        return BoardTile(self, color)


class BoardTile(Tile):

    def __init__(self, parent, color):
        super(BoardTile, self).__init__(front=parent.front, back=parent.back,
                                        front_commands=parent.front_commands,
                                        back_commands=parent.back_commands)
        self.color = color
        self.side = 'front'

    def flip(self):
        self.side = 'back' if self.side == 'front' else 'front'

    def action(self, x, y):
        return super(BoardTile, self).action(x, y, self.side)

    def command(self, x, y):
        return super(BoardTile, self).command(x, y, self.side)
