import os
import pygame
import random
import re

import level
import player
import tile
import block
import boulder
import lever
import level_bonus
import fadeout


class Level2(level.Level):
    def __init__(self, game, graphics_dir, paused=False):
        level.Level.__init__(self, game, graphics_dir, size=(64*5, 48*5),
                             paused=paused)

        self.dimensions = 5, 5

        for i in range(self.dimensions[0]):
            for j in range(self.dimensions[1]):
                self.tiles.append(
                    tile.Tile(self, i*64, j*48, self.imgs['ground1']))

        self.draw_background()

        bonus = level_bonus.Level(self.game, self.graphics_dir)
        self.objects.append(
            lever.Lever(
                self, 64 * 2, 48 * 3,
                [lambda setting:
                     fadeout.Fadeout(self.game, lambda: bonus.enter(self))],
                toggling=False,
                anim='lever_updown'))


    def load(self):
        """Load all resources used in the level."""
        tile_list = ['ground1', 'ground2']

        for tile in tile_list:
            self.imgs[tile] = pygame.image.load(os.path.join(
                    self.graphics_dir, 'tiles', '%s.png' % tile))

        block_list = ['block1']
        for block in block_list:
            self.imgs[block] = pygame.image.load(os.path.join(
                    self.graphics_dir, 'blocks', '%s.png' % block))

        # Load animations
        for anim, directory in (
            [('lever_updown', os.path.join('lever', 'down-up')),
             ]
            ):

            self.imgs[anim] = []

            # Find all image files for the given animation
            anim_files = []
            for root, dirs, files in os.walk(os.path.join(
                    self.graphics_dir, directory)):
                for f in files:
                    if re.match(r"^.*\.(png)$", '/'.join([root, f])):
                        anim_files.append('/'.join([root, f]))

            # Sort and load the files
            for f in sorted(anim_files):
                img = pygame.image.load(f)

                # Special treatment:
                if anim == 'arrow_left':
                    img = pygame.transform.flip(img, 1, 0)

                self.imgs[anim].append(img)

    def restart(self):
        for obj in self.objects:
            obj.reset_pos()