import pygame
pygame.init()

# Own modules
from game.classes.Text import Text
from game.classes.Timer import Timer
from game.classes.Preferences import *
from game.components import helpers

class Digital_Timer( Text ):
	def __init__( self, seconds, fps, text, centerxy, clock_tick_sound=None, no_formatting=False, unique_name=None, size=20, font="SysFont", color=BLACK, antialias=True, bold=False, italic=False, background=None, is_option=False ):
		super( Digital_Timer, self ).__init__( text, centerxy, unique_name, size, font, color, antialias, bold, italic, background, is_option )

		self._time = seconds * fps # Where to start the countdown from ?
		self._fps = fps # How many frames is a second ?

		self._mins = ""
		self._secs = ""

		self._no_formatting = no_formatting

		if clock_tick_sound == None:
			self._no_sound = True
		else:
			self._clock_tick_sound = helpers.load_sound( clock_tick_sound )
			sound_channel.play( self._clock_tick_sound )
			self._no_sound = False

		# Calculate minutes and seconds.
		self.calc_mins_secs()

		if not self._no_formatting:
			str1 = "{:0>2s}:{:0>1s}".format( str( self._mins ), str( self._secs ) )		
		else:
			str1 = str( self._secs )
			
		self.set_text( "%s" % str1 )

		# Set up a timer, that fires every second.
		self._timer = Timer( 0, self._fps, 1 )

	def calc_mins_secs( self ):
		self._mins = self._time // ( self._fps * 60 ) # A minute has 60 seconds.
		self._secs = ( self._time % ( self._fps * 60 ) ) // self._fps 

	def update( self ):
		"""
		"""
		if self._timer.update():
			# A second has passed.
			self._time -= self._fps			

			# Play the clock tick sound.
			if not self._no_sound and self._time is not 0:
				sound_channel.play( self._clock_tick_sound )
			 
			# Check if the time is over.
			if self._time == 0:
				return True
			else:
				# Otherwise update the text that is being displayed on the screen.
				self.calc_mins_secs()
				if not self._no_formatting:
					str1 = "{:0>2s}:{:0>2s}".format( str( self._mins ), str( self._secs ) )
				else:
					str1 = str( self._secs )
				self.set_text( "%s" % str1 )
