# This file is part of ROBOTGAME
#
# ROBOTGAME is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# ROBOTGAME is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# ROBOTGAME.  If not, see <http://www.gnu.org/licenses/>.
#
# ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
#
#                          player.py
#                     --------------------
#       date created : Tue Aug 7 2012
#          copyright : (C) 2012 Sakse Dalum
#      maintained by : Sakse Dalum <don_s@hongabar.org>

"""
The player.
"""

import pygame
import re
import os

import worldobject
import boulder
import lever

class Player(worldobject.WorldObject):
    def __init__(self, level, x, y, z=1, movable=True):
        self.__dict__.update(locals())
        worldobject.WorldObject.__init__(self, level, x, y,
                                         z=z, movable=movable)

        self.anim_root = 'idle'
        self.anim = 'right'
        self.frame = 0
        self.anim_speed = 15

        self.working = False

        self.ignore_list.append(boulder.Boulder)

        self.load()

    def load(self):
        self.imgs = {}

        for anim, directory in (
            [('idle_up', os.path.join('robot_idle', 'up')),
             ('idle_down', os.path.join('robot_idle', 'down')),
             ('idle_right', os.path.join('robot_idle', 'right')),
             ('idle_left', os.path.join('robot_idle', 'right')),
             ('carry_up', os.path.join('robot_carry', 'up')),
             ('carry_down', os.path.join('robot_carry', 'down')),
             ('carry_right', os.path.join('robot_carry', 'right')),
             ('carry_left', os.path.join('robot_carry', 'right')),

             # Lever

             ('lever_down_right', os.path.join('robot_lever', 'horizontal',
                                               'down_left')),
             ('lever_down_left', os.path.join('robot_lever', 'horizontal',
                                              'down_left')),
             ('lever_down_up', os.path.join('robot_lever', 'vertical',
                                            'down_down')),
             ('lever_down_down', os.path.join('robot_lever', 'vertical',
                                              'down_down')),

             ('lever_up_right', os.path.join('robot_lever', 'horizontal',
                                               'up_right')),
             ('lever_up_left', os.path.join('robot_lever', 'horizontal',
                                              'up_right')),
             ('lever_up_up', os.path.join('robot_lever', 'vertical',
                                            'up_up')),
             ('lever_up_down', os.path.join('robot_lever', 'vertical',
                                              'up_up')),

             ('lever_right_right', os.path.join('robot_lever', 'horizontal',
                                               'right_right')),
             ('lever_right_left', os.path.join('robot_lever', 'horizontal',
                                              'right_right')),
             ('lever_right_up', os.path.join('robot_lever', 'vertical',
                                            'left_up')),
             ('lever_right_down', os.path.join('robot_lever', 'vertical',
                                              'right_down')),

             ('lever_left_right', os.path.join('robot_lever', 'horizontal',
                                               'right_right')),
             ('lever_left_left', os.path.join('robot_lever', 'horizontal',
                                              'left_left')),
             ('lever_left_up', os.path.join('robot_lever', 'vertical',
                                            'left_up')),
             ('lever_left_down', os.path.join('robot_lever', 'vertical',
                                              'right_down'))
             ]
            ):

            self.imgs[anim] = []

            # Find all image files for the given animation
            anim_files = []
            for root, dirs, files in os.walk(os.path.join(
                    self.level.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 in ['idle_left', 'carry_left',

                            'lever_down_right', 'lever_left_down',
                            'lever_up_left', 'lever_right_up']:
                    img = pygame.transform.flip(img, 1, 0)

                if anim in ['lever_right_left', 'lever_left_right',
                            'lever_down_up', 'lever_up_down']:
                    self.imgs[anim].insert(0, img)
                else:
                    self.imgs[anim].append(img)

        self.img = self.imgs[self.anim_root + '_' + self.anim][int(self.frame)]

    def direction_as_string(self):
        if self.direction == (1, 0):
            return "right"
        if self.direction == (-1, 0):
            return "left"
        if self.direction == (0, -1):
            return "up"
        if self.direction == (0, 1):
            return "down"

    def touch(self, touch_x, touch_y):
        for obj in self.level.objects:
            if (obj.x == self.x + touch_x * self.tile_x
                and obj.y == self.y + touch_y * self.tile_y
                and obj != self):

                # Concerning levers
                if type(obj) == lever.Lever:
                    if not obj.at_rest:
                        return

                    obj.use(self)
                    self.working = True

                    # List all possible combinations ...
                    lever_direction = (
                        'up' if obj.anim == 'lever_updown' and not obj.setting
                        else
                        'right' if obj.anim == 'lever_leftright'
                                and not obj.setting
                        else
                        'down' if obj.anim == 'lever_updown' and obj.setting
                        else
                        'left')

                    self.anim_root = 'lever'
                    self.frame = 0
                    self.anim = (
                        self.direction_as_string() + '_' + lever_direction)
                else:
                    obj.use(self)

    def update(self, e, t, dt):
        if not self.working:
            self.anim_root = 'carry' if self.holding else 'idle'

            keys = pygame.key.get_pressed()
            if keys[pygame.K_UP]:
                if not self.holding and not self.is_moving:
                    self.direction = (0, -1)
                    self.anim = self.direction_as_string()
                self.move(0, -1)
            elif keys[pygame.K_DOWN]:
                if not self.holding and not self.is_moving:
                    self.direction = (0, 1)
                    self.anim = self.direction_as_string()
                self.move(0, 1)
            elif keys[pygame.K_RIGHT]:
                if not self.holding and not self.is_moving:
                    self.direction = (1, 0)
                    self.anim = self.direction_as_string()
                self.move(1, 0)
            elif keys[pygame.K_LEFT]:
                if not self.holding and not self.is_moving:
                    self.direction = (-1, 0)
                    self.anim = self.direction_as_string()
                self.move(-1, 0)

            for event in e:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.touch(*self.direction)

        else:
            self.working = not (self.frame == len(
                    self.imgs[self.anim_root + '_' + self.anim]) - 1)
            if not self.working:
                self.anim = self.direction_as_string()
                self.anim_root = 'carry' if self.holding else 'idle'

        # Update the animation
        if not self.working:
            self.frame = ((self.frame + self.anim_speed * dt) %
                          len(self.imgs[self.anim_root + '_' + self.anim]))
        else:
            self.frame = min(
                self.frame + self.anim_speed * dt,
                len(self.imgs[self.anim_root + '_' + self.anim]) - 1)


        worldobject.WorldObject.update(self, e, t, dt)

    def draw(self, window):
        self.img = self.imgs[self.anim_root + '_' + self.anim][int(self.frame)]
        self.img.set_alpha(128)
        offset_x = (96 if self.anim_root == 'lever' and self.anim in
                    ['left_up', 'left_left', 'left_down', 'left_right',
                     'down_right', 'up_left']
                    else 32)
        window.blit(self.img, (self.x - offset_x - self.level.camera_x,
                               self.y - self.img.get_size()[1] + 24
                               - self.level.camera_y))