# -*- coding: utf-8 -*-

# Copyright (c) 2006 Stas Zykiewicz <stas.zytkiewicz@gmail.com>
#
#           soundNpic.py
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public License
# as published by the Free Software Foundation.  A copy of this license should
# be included in the file GPL-2.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

RCFILE = 0

import os,sys,operator,random
import pygame
from pygame.constants import *
from utils import load_image,load_sound,MyError,get_files


class Img:
    pass
class Snd:
    pass

class PicSnd:
    def __init__(self,pic,snd,move,start,end):
        self.snd = snd
        self.image = pic
        self.original = pic
        self.move = -move
        self.orgmove = move
        self.end = end
        self.start = start
        self.count = start[1]
        self.rect = self.image.get_rect().move(start)
        self.dizzy = 0
        self.flag = 0
        
    def update(self):
        
        if self.dizzy:
            self._spin()
        else:
            self._updown()
        self.count += self.move
        return self.flag
    
    def _updown(self):
        self.flag = 0
        self.rect = self.rect.move(0,self.move)
        if self.count <= self.end[1]:
            self.count = self.start[1]
            self.dizzy = 1
        if self.rect[1] >= self.start[-1]:
            self.rect = self.image.get_rect().move(self.start)
            self.move = -self.orgmove
            self.count = self.start[1]
            self.flag = 1
                
    def _spin(self):
        # Copy of the spin in pygame chimp, and a little bit of me
        center = self.rect.center
        self.dizzy = self.dizzy + 12
        #print self.dizzy,self.count,self.move
        if self.dizzy >= 360:
            self.dizzy = 0
            self.image = self.original
            self.move = -self.move/3
            self.count = self.end[1]
            #print self.move
        else:
            self.image = pygame.transform.rotate(self.original, self.dizzy)
        self.rect = self.image.get_rect()
        self.rect.center = center
    
    # Not used
    def erase(self):
        self.rect = Img.screen.blit(Img.backgr,self.rect,self.rect)
        
class Game(Img,Snd):    
    """  soundNpic.py - part of childsplay.py, a suite of educational games for
  young children."""

    def __init__(self,screen,backgr,rcdic,basepath,libdir,cpg):
        Img.screen = screen
        Img.backgr = backgr
        self.gamelevels = ('Level1',)
        self.gameitems = (1,)
        self.rcdic = rcdic
        self.basedir  = basepath
        self.libdir = libdir
        self.stop = 0
        self.score = 0
        self._setup()

    def _setup(self):
        self.objs_to_move = []
        
    def start(self,level,i):
        """Hit a image and listen to the sound, it doesn't do much more, for now"""
        try:
            wavfiles = get_files(os.path.join(self.libdir,'SoundNpicData',level),'*.ogg')
        except MyError,info:
            MyError.line = 110
            MyError.name = __name__
            raise MyError,info
        # loose the .ogg
        filenames = map(operator.getslice,wavfiles,(0,)*len(wavfiles),(-4,)*len(wavfiles))
        objlist = []
        self.objdict = {}
        self.rectlist = []
        x = 10
        offset = 10
        y = 325
        random.shuffle(filenames)
        try:
            for item in filenames:
                img = load_image(os.path.join(self.libdir,'SoundNpicData',level,item+'.png'),1)
                snd = os.path.join(self.libdir,'SoundNpicData',level,item+'.ogg')
                obj = PicSnd(img,snd,12,(x,y),(x,y-250))
                objlist.append((obj))
                x = x + obj.image.get_width()+ offset
                
        
        except MyError,info:
            MyError.line = 'method start()'
            MyError.name = __name__
            raise MyError,info
       
        for obj in objlist:
            r = self.screen.blit(obj.image,obj.rect)
            self.objdict[tuple(r)] = obj
            self.rectlist.append((r))
            
        pygame.display.update(self.rectlist)
        
        
    def loop(self,events):
        for event in events:
            if event.type is MOUSEBUTTONDOWN and self.objs_to_move == []:
                self._select_activate()
        obj_remove,dirty_rects = [],[]
        # main blit stuff
        for obj in self.objs_to_move:
            dirty_rects.append((self.screen.blit(self.backgr,obj.rect,obj.rect)))
            flag = obj.update()
            dirty_rects.append((self.screen.blit(obj.image,obj.rect)))
            if flag == 1: # obj returns 1 if finished
                obj_remove.append((obj))
        
        pygame.display.update(dirty_rects)
        if obj_remove:
            self.objs_to_move.pop()
        return self.stop,self.score

    def _select_activate(self):
        pos = pygame.Rect(pygame.mouse.get_pos() + (4,4))
        for rec in self.rectlist:
            if rec.contains(pos):
                obj = self.objdict[tuple(rec)]
                # Set up sound events
                playmusic = pygame.mixer.music
                try:
                    file = obj.snd
                    playmusic.load(file) 
                except pygame.error,info:
                    print >> sys.stderr,info,"\nDisable music"
                    class NoneSound:
                        def play(self,loop=None):
                            pass
                
                    playmusic = NoneSound()
                playmusic.play(2)
                self.objs_to_move.append((obj))
        return
    
    def helptitle(self):
        return 'SoundNpic'

    def __str__(self):
        """Must return the original, not translated, title of this game.
        It's needed by the high score class of childsplay."""        
        return "SoundNpic"


    def help(self):
        text = [_("The aim of the game:"),
        _("Click on a picture and listen to the sound."),
        " ",
        _("Difficulty : 2-3 years"),
        " ",
        _("Number of levels : 1"),
        " ",
        _("Due to the size of the module, mostly pictures and sounds, it's"),
        _("split in separate modules instead of levels.")]

        return text
