#!/usr/bin/env python

# from shortcrust import has_glut
# SOUND_ENABLED = not has_glut  # enable sound on raspi only
SOUND_ENABLED = True

from shortcrust import BaseGLApp
from shortcrust.mesh import Mesh
from shortcrust.gl2 import *
from effects.background import BackgroundLayer
from effects.toast import ToastLayer
from effects.rainbows import RainbowLayer
from effects.champion import ChampionLayer
from effects.lyrics import LyricsLayer
from effects.ring import RingLayer

if SOUND_ENABLED:
	import pygame

# global constants
FREQ = 44100   # same as audio CD
BITSIZE = -16  # unsigned 16 bit
CHANNELS = 2   # 1 == mono, 2 == stereo
BUFFER = 1024  # audio buffer size in no. of samples
FRAMERATE = 30  # how often to check if playback has finished

MUSIC_BPM = 95.0


identity_matrix = GLfloats(
	(1.0, 0.0, 0.0, 0.0,
	0.0, 1.0, 0.0, 0.0,
	0.0, 0.0, 1.0, 0.0,
	0.0, 0.0, 0.0, 1.0)
)


class ToastMesh(Mesh):
	mode = GL_TRIANGLE_FAN
	vertices = [
		(0.00, 0.29, 0.00),
		(0.27, 0.30, 0.00),
		(0.30, 0.28, 0.00),
		(0.29, 0.27, 0.00),
		(0.30, -0.30, 0.00),
		(-0.30, -0.30, 0.00),
		(-0.29, 0.27, 0.00),
		(-0.30, 0.28, 0.00),
		(-0.27, 0.30, 0.00),
	]


class AvocadoDemo(BaseGLApp):
	title = "Avocado on toast!"

	def setup(self):
		print """
'Avocado'

A demo for the Raspberry Pi
presented at Evoke 2012

Code and graphics..........Gasman - http://matt.west.co.tt/
Music...............ihatemornings - http://ihatemornings.com/

from an original tweet by @aliteralgirl:
http://twitter.com/aliteralgirl/status/3085083121

Greetings to RBBS. :-)
		"""
		bg_layer = BackgroundLayer(self)
		check_gl_error()
		toast_layer = ToastLayer(self)
		check_gl_error()
		self.layers = [
			bg_layer,
			RingLayer(self),
			toast_layer,
			RainbowLayer(self),
			LyricsLayer(self),
			ChampionLayer(self),
		]
		#glClearColor(0.0, 0.0, 0.0, 1.0)  # This Will Clear The Background Color To Black

		self.beat_length = 60.0 / MUSIC_BPM

		if SOUND_ENABLED:
			try:
				pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
			except pygame.error, exc:
				print >>sys.stderr, "Could not initialize sound system: %s" % exc
				return 1
			#sound = pygame.mixer.Sound('data/avocado.mp3')
			#sound.play()
			pygame.mixer.music.load('data/avocado.mp3')
			pygame.mixer.music.play()

		glEnable(GL_DEPTH_TEST)
		glEnable(GL_BLEND)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

	def draw(self, time):
		glViewport(0, 0, self.width, self.height)

		# Clear The Colour Buffer
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

		for layer in self.layers:
			layer.draw(time)

	def exit(self):
		if SOUND_ENABLED:
			pygame.mixer.music.stop()
			pygame.mixer.quit()


# and kick off the main to get it rolling.
AvocadoDemo().run()
