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

# Copyright (c) 2007 Stas Zykiewicz <stas.zytkiewicz@gmail.com>
#
#           splash.py
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 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-3.
#
# 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.

_DEBUG = 1


import pygame,os,sys
pygame.init()
scr = pygame.display.set_mode((800,600))

from threading import Thread
from utils import trace_error,load_image,load_music
from CPConstants import DATADIR


class Worker:
    def __init__(self):
        self.timeout = 10000
        self.runsplash = True
        try:
            self.thread = Thread(target=self._start_splash)
            self.thread.start()
            pygame.time.wait(2)
        except Exception,info:
            print info
            print "Failed to start splash"
            self.runsplash = None
    
    def __del__(self):
        try:
            if _DEBUG: print >> sys.stderr,__name__,"__del__ called"
            self.stop_splash()
        except:
            pass

    def _start_splash(self):
        """Display a splash screen at startup.
          This runs in a seperate thread at the timeout or until it gets terminated
          through a call to stop_splash."""
        try:
            snd = load_music(os.path.join(DATADIR,'SpaceComputer.ogg'))
            snd.play(-1)
        except pygame.error,info:
            print >> sys.stderr,info
        try:
            cow = load_image(os.path.join(DATADIR,'loading_splash.jpg'))
            pygame.display.update(scr.blit(cow,(0,0)))
        except (Exception,pygame.error),info:
            try:
                snd.stop()
            except:
                pass
            trace_error()
            self.runsplash = None
        count = 0
        while self.runsplash:
            pygame.time.wait(200)
            count += 50
            if count >= self.timeout:
                self.runsplash = None
        try:
            snd.stop()
        except:
            pass
    
    def stop_splash(self):
        if _DEBUG: print "stop_splash called"
        pygame.time.wait(3000)
        self.runsplash = None

 
