import pygame
from pygame.locals import *
from copy import copy
import os
import math

from anim import Animation
from gui import Gui
from item import Item
import map as map_

from locals import *

class Rect:
    def __init__(self, x, y, w, h):
        self.left = x
        self.top = y
        self.width = w
        self.height = h
        self.right = x + w
        self.bottom = y + h

class Object:
    def __init__(self, name, pos=(0.0,0.0)):
        self.name = name

# Assigns default values for a stationary object
        self.animations = {}
        self.center = [0,0]
        self.size = [0,0]
        self.dir = [0,0]

        self.pos = pos
        self.current_animation = None
        self.selected = False
        self.health = MAX_HEALTH
        self.objtype = TYPE_OBJECT
        self.dead = False
        self.inventory = []

# Read the real values from file
        f = open(os.path.join("objects", name) + ".txt")

        defaultanim = Animation()
        currentanim = defaultanim

        invsize = 0
        for line in f.readlines():
            values = line.split()
            variable, values = values[0], values[1:]
            if invsize > 0:
                invsize -= 1
                self.inv_add_item(variable, int(values[0]))
            elif variable == "animation":
# Opens an animation with the name "objectname_animationname"
                animation_name = values[0]
                currentanim = copy(defaultanim)
                currentanim.load_surface(self.name, animation_name)
                if len(self.animations) == 0:
                    self.animations["default"] = currentanim
                self.animations[animation_name] = currentanim
            elif variable == "frames":
                frames = int(values[0])
                currentanim.set_frames(frames)
            elif variable == "center":
                x = int(values[0])
                y = int(values[1])
                currentanim.center = (x,y)
            elif variable == "size":
                w = float(values[0])
                h = float(values[1])
                currentanim.size = (w,h)
            elif variable == "dir":
                x = float(values[0])
                y = float(values[1])
                currentanim.dir = (x,y)
            elif variable == "walkover":
                currentanim.walkover = True
                currentanim.walkoverlevel = int(values[0])
            elif variable == "inventory":
                 invsize = int(values[0])

        if len(self.animations) == 0:
            defaultanim.load_surface(self.name)
            self.animations["default"] = defaultanim

        self.set_animation("default")

    def set_animation(self, anim_name):
        self.current_animation = self.animations[anim_name]
        self.center = self.current_animation.center
        self.dir = self.current_animation.dir
        self.size = self.current_animation.size

    # We don't use the map here, but it's for compatibility with the
    # Character class
    def update(self, map_):
        self.current_animation.update()
        if self.current_animation.name == "dying_south" and (self.current_animation.frame == (self.current_animation.frames - 1)):
           self.set_animation("dead")

        # This just sums the elements of  pos and dir together
        self.pos = map(sum, map(None, self.pos, self.dir))

    def draw(self, screen, offset):
# Sum
        drawpos = map_.get_screen_pos(offset, self.pos)

        self.current_animation.draw(screen, drawpos)
        if self.selected:
           hrect = Gui.selecthp.get_rect()
           hrect.width = self.health
           screen.blit(Gui.selectarrow, (drawpos[0]-6, drawpos[1]-50))
           screen.blit(Gui.selecthp, (drawpos[0]-5, drawpos[1]-49), hrect)

    def get_rect(self):
        return Rect(self.pos[0]-self.size[0]/2,self.pos[1]-self.size[1]/2,
                    self.size[0],self.size[1])
        #return (self.pos[0] - self.size[0]/2, self.pos[1] - self.size[1]/2,
        #        self.pos[0] + self.size[0]/2, self.pos[1] + self.size[1]/2)

# This isn't really what we want to do, but it'll do for now.
    def stop(self):
        self.dir = (0.0, 0.0)
        if self.dead:
            return
        self.set_animation("idle_" + self.direction_from_anim())

    def inv_add_item(self, name, amount):
        self.inventory.append(Item(name, amount))

    def distance(self, obj):
        dx = obj.pos[0] - self.pos[0]
        dy = obj.pos[1] - self.pos[1]
        return math.sqrt(dx*dx + dy*dy)

    def direction_from_anim(self):
        if self.current_animation.name.endswith("east"):
           return "east"
        if self.current_animation.name.endswith("south"):
           return "south"
        if self.current_animation.name.endswith("north"):
           return "north"
        if self.current_animation.name.endswith("west"):
           return "west"
        return "south"

    def is_walkover(self):
        return self.current_animation.walkover

def main():
    pygame.init()

    screen = pygame.display.set_mode((640,480))

    obj = Object("walker")

    done = False

    while not done:
        for e in pygame.event.get():
            if e.type == QUIT:
                done = True
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                done = True

        screen.fill((0,0,0))

        obj.draw(screen, (300,200))
        obj.update()

        pygame.display.flip()

if __name__ == "__main__":
    main()
