#Import Modules
import os, pygame
from load import Load
class View:
    """this class is for paint al creatures in a window the screen object"""
    load = Load()
    sizeX = 600
    sizeY = 600
    
    def __init__(self, evManager):
        """__init__(self) -> returns nothing
        is for iniatilaizing evrethyings the view needs"""
        
        #set the eventManager to hear and raises events
        self.evManager = evManager
        self.evManager.RegisterListener( self, "view" )
        #iner method for set pygames needs
        self.initPygame()
        #for now sets the background with a specific size in the future
        #will set the size in more dinamic way
        self.background = pygame.Surface((400, 400))
        #---------------------------------------------
        
    def  Notify(self, event):
        """Notify(self, event):
        with this metod the view can hear events lauched in the controller,
        and in the model"""

        #hear for addSomthing events and call some the methods in response  
        if event.name  == 'AddSpriteEvent':
            self.setSprite(event.group)
        elif event.name ==  'SetSurfaceEvent':
            self.setBackground(event.array)

        #hear for update somthing events and call some the methods in response
        elif event.name == 'UpdateSpriteEvent':
            self.updateSprite(event.group)
        elif event.name == 'UpdateSurfaceEvent':
            self.updateBakground(event.array, event.group)    
                elif event.name ==  'UpdateSpriteGroupEvent':
            self.updateSpriteGroup(event.group)
            
             #---------------------------------------------
            
    def initPygame(self):
        """initPygame(self): this method is for call all init parts of
        pygame and create the sprite group and diccionary of sprites"""
        pygame.init()
        self.bugContainer = {}
        self.group = pygame.sprite.RenderUpdates() 
        self.setScreeen()
         #---------------------------------------------

    # __________________________setSomething methods________________________
    
    def setBackground(self, array):
        """setBackground(self, surface):
        sets the background with the surface created in the model"""
        #Create The Backgound
        self.background = pygame.surfarray.make_surface(array)
        self.background = self.background.convert()
        #Display The Background
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()
         #---------------------------------------------

    def setScreeen(self):
        """setScreeen(self)
        sets the display part of pygame -->pygame.display.set_mode"""
        #for now set the displaying screen with a fixed sice
        #in the future will have more dinamic way to doit
        self.screen = pygame.display.set_mode((View.sizeX, View.sizeY))
        pygame.display.set_caption('MUNDITO')
        #---------------------------------------------

    def setSprite(self, creature):
        """setSprite(self, name, properties)
        name = string
        properties  = list
        returns -> nothing
        is for add a sprite in the display frame"""
        #display the new sprite
        pygame.display.update(self.draw(self.screen, creature))
        #necesary to remove in the future the images if the images change
        creature.clear(self.screen, self.background)
        #---------------------------------------------

    def removeSprite(self, name):
        """  removeSprite(self, name)
        name = string
        returns -> nothing
        remove a sprite from the game"""
        #for now dont do nothing in the future will have to
        #kill the sprites on all the the groups belong to and
        #updatte the screen image
        self.bugContainer[name].kill()
        self.bugContainer[actor].remove()
        self.update()
        #---------------------------------------------

    # getSomething methods

    def getBackground(self):
        """getBackground(self)
            returns -> surface"""
        return self.background
        #---------------------------------------------

    def getScreen(self):
        """ getScreen(self)
            returns -> surface"""
        return self.screen
        #---------------------------------------------
    
    def getSprite(self, name):
        """ getSprite(self, name)
            name = string
            returns -> Sprite object"""
        return self.bugContainer[name]
        #---------------------------------------------

    def getSpriteGroup(self):
        """getSpriteGroup(self)
        returns -> a list of the sprites in the group"""
        return self.goup
        #---------------------------------------------
    
    #Update methods

    def updateSprite(self, creature):
        """updateSprite(self, name, properties)
        name = string
        properties = list
        returns -> nothing
        this method update the internal atributes of the sprites and
        update is image in the screen if the properties change"""
        #update sprites and draw it in the screen 
        pygame.display.update(self.draw(self.screen, creature))
        #clear the old images of the screen
        creature.clear(self.screen, self.background)
        
        #---------------------------------------------
        
    def updateBakground(self, array, group):
        """updateBakground(self, array)"""

        #convert the array of the modell in to teh surface background
        self.background = pygame.surfarray.make_surface(array)

        #update the images of the sprites(creatures) in the background 
        for element in group.sprites():
            a = (element.rect.x, element.rect.y) 
            self.background.blit(element.image,a)
        self.background = self.background.convert()

        #Display The Background
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()    
        #---------------------------------------------
        
    def updateSpriteGroup(self, creatures):
        """updateSpriteGroup(self)
        returns -> nothing
        this method update all the sprites and the backgraund in
        the screen"""

        # update the sprites and draw them in the screen
        pygame.display.update(self.draw(self.screen, creatures))

        # remove the old images
        creatures.clear(self.screen, self.background)
        #---------------------------------------------
    
    
     # other methods   
      
    def createImages(self, sprite):
        """ createImages(self, sprite)
            returns -> nothing
            this metod add a image to some sprite """
        image = self.load.load_image("chimp.bmp", -1)
        sprite.setImage(image, image.get_rect())
         #---------------------------------------------
    


    

    def draw(self, surface, group):
        """draw(surface)
           draw all sprites onto the surface

           Draws all the sprites onto the given surface. It
           returns a list of rectangles, which should be passed
           to pygame.display.update()"""
        
        spritedict = group.spritedict
        surface_blit = surface.blit
        dirty = group.lostsprites
        self.lostsprites = []
        dirty_append = dirty.append
        for s, r in spritedict.items():
            newrect = surface_blit(s.image, s.rect)
            if r is 0:
                dirty_append(newrect)
            else:
                if newrect.colliderect(r):
                    dirty_append(newrect.union(r))
                else:
                    dirty_append(newrect)
                    dirty_append(r)
            spritedict[s] = newrect
        return dirty
#--------------------------------------------------------------------------------------------------------------------
#-----------------------------------------End of view class---------------------------------------------------
#--------------------------------------------------------------------------------------------------------------------

class Load:
    """class Load
    this class is for load all the resources the images and the music
    in the game"""   
        
    #functions to create our resources
    def load_image(self, name, colorkey=None):
        """load_image(self, name, colorkey=None)
        name = string  name of the image
        colorkey = float  transparenci of the image
        returns -> a image and a rect object for the image """
        #creat the path for the image 
        fullname = os.path.join('images', name)
        #try to download the image
        try:
            image = pygame.image.load(fullname)
        except pygame.error, message:
            print 'Cannot load image:', fullname
            raise SystemExit, message
        # pygame convert the image in the best formate for especific
        #properties of the sistem
        image = image.convert()
        return image 
    

    def load_sound(self, name):
        """load_sound(self, name)
        name = string  the name of the sound 
        returns -> a sound"""
        class NoneSound:
            def play(self): pass
        if not pygame.mixer or not pygame.mixer.get_init():
            return NoneSound()
        # create the path for the sound
        fullname = os.path.join('sounds', name)
        #try to download the sound
        try:
            sound = pygame.mixer.Sound(fullname)
        except pygame.error, message:
            print 'Cannot load sound:', fullname
            raise SystemExit, message
        return sound
        
       
        

        
        
        
    
