import arcade

CELL = 25
HEIGHT = 600
WIDTH = 900
TITLE = "OGS Memory"

class Context:
  def __init__(self):
    self.images = [
      ["res/tiles.png", 0, 0, 75, 100],
      ["res/tiles.png", 75, 0, 75, 100],
      ["res/tiles.png", 150, 0, 75, 100],
    ]

    self.positions = [
      [9, 1],
      [14, 1],
      [19, 1],
      [24, 1],

      [9, 7],
      [14, 7],
      [19, 7],
      [24, 7],

      [9, 13],
      [14, 13],
      [19, 13],
      [24, 13],

      [9, 19],
      [14, 19],
      [19, 19],
      [24, 19],
    ]
    self.textures = None
    self.deselected_tiles = None
    self.selected_tiles = None

class Window(arcade.Window):
  def __init__(self):
    super().__init__(WIDTH, HEIGHT, TITLE)
    arcade.set_background_color(arcade.color.WHITE)
    self.all_sprites = arcade.SpriteList()
    self.c = Context()
    c = self.c

    c.textures = load_textures(c.images)
    c.deselected_tiles = create_deselected_tiles(c.positions, c.textures)
    for t in c.deselected_tiles:
      self.all_sprites.append(t)
    c.selected_tiles = create_selected_tiles(c.positions, c.textures)
    for t in c.selected_tiles:
      self.all_sprites.append(t)

  def on_draw(self):
    arcade.start_render()
    self.all_sprites.draw()

  def on_mouse_press(self, x, y, button, key_modifiers):
    print("click", x, y)
    sprites = arcade.get_sprites_at_point([x, y], self.all_sprites)
    id = sprites[0].guid
    print("selected id: ", id)
    #print("deselected_tiles: ", self.c.deselected_tiles)
    #print("selected_tiles: ", self.c.selected_tiles)
    self.c.deselected_tiles[id].visible = False
    self.c.selected_tiles[id].visible = True

  def on_update(self, delta):
    self.all_sprites.update_animation()


def load_textures(images):
  ts = []
  for (id, img) in enumerate(images):
    tex = arcade.load_texture(img[0], x = img[1], y = img[2], width = img[3], height = img[4])
    ts.append(tex)
  return ts

def create_deselected_tiles(positions, textures):
  tiles = []
  for (id, p) in enumerate(positions):
    tile = arcade.AnimatedTimeBasedSprite()
    tiles.append(tile)
    tile.guid = id
    tile.texture = textures[0]
    # Animation between two textures.
    a1 = arcade.sprite.AnimationKeyframe(0, 700, textures[0])
    a2 = arcade.sprite.AnimationKeyframe(1, 700, textures[1])
    tile.frames.append(a1)
    tile.frames.append(a2)
    # Position.
    tile.center_x = CELL * 2 + p[0] * CELL
    tile.center_y = HEIGHT - CELL * 2 - p[1] * CELL
  return tiles

def create_selected_tiles(positions, textures):
  tiles = []
  for (id, p) in enumerate(positions):
    tile = arcade.Sprite()
    tiles.append(tile)
    tile.guid = id
    tile.texture = textures[2]
    # Position.
    tile.center_x = CELL * 2 + p[0] * CELL
    tile.center_y = HEIGHT - CELL * 2 - p[1] * CELL
    # Invisible by default.
    tile.visible = False
  return tiles
