#!/bin/env python2.7
# -*- coding: utf-8 -*-

# This file is part of AP - Assistive Prototypes.
#
# AP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# AP 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AP. If not, see <http://www.gnu.org/licenses/>.

import wxversion
# wxversion.select( '2.8' )

import glob, os, time, sys
import wx, alsaaudio, psutil
import wx.lib.buttons as bt

from pymouse import PyMouse
from pygame import mixer

import suspend

#=============================================================================
class pilot(wx.Frame):
	def __init__(self, parent, id):

	    self.winWidth, self.winHeight = wx.DisplaySize( )

            self.initializeParameters( )
            wx.Frame.__init__( self , parent , id, 'audiobookPilot', size = ( self.width, self.height ), pos = ( self.winWidth - self.width - self.xBorder*(self.numberOfColumns[0]-2)+10, self.winHeight - self.height - self.xBorder*(self.numberOfRows[0]-5) + 10) ) 
            self.SetBackgroundColour( 'black' )
	    
            style = self.GetWindowStyle( )
            self.SetWindowStyle( style | wx.STAY_ON_TOP )
	    self.parent = parent
            
	    self.MakeModal( True )		
	    
            self.initializeBitmaps( )
            self.createGui( )								
            self.createBindings( )						

            self.initializeTimer( )					

	#-------------------------------------------------------------------------
	def initializeParameters(self):

            with open( './.pathToAP' ,'r' ) as textFile:
                self.pathToAP = textFile.readline( )
                
	    sys.path.append( self.pathToAP )
	    from reader import reader
	    
            self.reader = reader()
            self.reader.readParameters()
            parameters = self.reader.getParameters()
            self.unpackParameters(parameters)
                        
            self.flag = 'row'
	    self.pressFlag = False
            self.pressedStopFlag = False

            self.numberOfColumns = 2,
            self.numberOfRows = 6,
	    
            self.colIteration = 0
            self.panelIteration = 0
            self.rowIteration = 0						
            
	    self.numberOfEmptyIteration = 0
            self.countRows = 0
            self.countColumns = 0
            self.countMaxRows = 2									
            self.countMaxColumns = 2									
            self.numberOfPresses = 1

            self.volumeLevels = [0, 20, 40, 60, 80, 100, 120, 140, 160]
            if self.volumeLevel not in self.volumeLevels:
                raise("Wrong value of volumeLevel. Accepted values: 0, 20, 40, 60, 80, 100, 120, 140, 160")

	    if self.control != 'tracker':
		    self.mouseCursor = PyMouse( )
		    self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
		    self.mouseCursor.move( *self.mousePosition )	

	    if self.switchSound.lower( ) != 'off' or self.pressSound.lower( ) != 'off':
		    mixer.init( )
                    self.switchingSound = mixer.Sound( self.pathToAP + '/sounds/switchSound.ogg' )
                    self.pressingSound = mixer.Sound( self.pathToAP + '/sounds/pressSound.ogg' )

                    self.ciszejSound = mixer.Sound( self.pathToAP + '/sounds/ciszej.ogg' )
                    self.glosniejSound = mixer.Sound( self.pathToAP + '/sounds/glosniej.ogg' )

                    self.przewinDoPrzoduPowoliSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu_powoli.ogg' )
                    self.przewinDoPrzoduSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu.ogg' )
                    self.przewinDoPrzoduSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu_szybko.ogg' )
                    self.przewinDoTyluPowoliSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu_powoli.ogg' )
                    self.przewinDoTyluSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu.ogg' )
                    self.przewinDoTyluSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu_szybko.ogg' )

                    self.zatrzymajGrajSound = mixer.Sound( self.pathToAP + '/sounds/zatrzymaj_graj.ogg' )
                    self.stopSound = mixer.Sound( self.pathToAP + '/sounds/stop.ogg' )

                    self.wyjscieSound = mixer.Sound( self.pathToAP + '/sounds/wyjście.ogg' )
                    self.powrotSound = mixer.Sound( self.pathToAP + '/sounds/powrot.ogg' )

                    self.oneSound = mixer.Sound( self.pathToAP + '/sounds/rows/1.ogg' )
                    self.twoSound = mixer.Sound( self.pathToAP + '/sounds/rows/2.ogg' )
                    self.threeSound = mixer.Sound( self.pathToAP + '/sounds/rows/3.ogg' )
                    self.fourSound = mixer.Sound( self.pathToAP + '/sounds/rows/4.ogg' )
                    self.fiveSound = mixer.Sound( self.pathToAP + '/sounds/rows/5.ogg' )
                    self.sixSound = mixer.Sound( self.pathToAP + '/sounds/rows/6.ogg' )
            
	    self.width = self.numberOfColumns[0] * 120
	    self.height = self.numberOfRows[0] * 100

        #-------------------------------------------------------------------------	
        def unpackParameters(self, parameters):

		for item in parameters:
			try:
				setattr(self, item[:item.find('=')], int(item[item.find('=')+1:]))
			except ValueError:
				setattr(self, item[:item.find('=')], item[item.find('=')+1:])

	#-------------------------------------------------------------------------	
        def initializeBitmaps(self):

            buttonPaths = glob.glob( self.pathToAP + 'icons/pilots/audiobookPilot/*' ) #labelFiles
            
            self.buttons = { }

            for buttonPath in buttonPaths:

                buttonBitmap = wx.BitmapFromImage( wx.ImageFromStream( open(buttonPath, "rb") ) )

                buttonLabel = buttonPath[ buttonPath.rfind( '/' )+1 : buttonPath.rfind('.') ]
                try:
                    buttonPosition = int( buttonLabel.split( '_' )[ 0 ] )
                    buttonName = buttonLabel[ buttonLabel.find( '_' )+1: ]
                    self.buttons[ buttonPosition ] = [ buttonName, buttonBitmap ]
                    
                except ValueError:
                    print 'Symbol %s ma nieprawidłową naz
wę.' % ( buttonLabel )
                    pass

	#-------------------------------------------------------------------------
	def createGui(self):

		self.mainSizer = wx.BoxSizer( wx.VERTICAL )

		self.subSizer = wx.GridBagSizer( self.xBorder, self.yBorder )

		if self.control != 'tracker':
			event = 
eval('wx.EVT_LEFT_DOWN')
		else:
			event = eval('wx.EVT_BUTTON')
		
		for key, value in self.buttons.items( ):
				b = bt.GenBitmapButton( self, -1, name = value[ 0 ], bitmap = value[ 1 ] )
				b.SetBackgroundColour( self.backgroundColour )
				b.SetBezelWidth( 3 )
				b.Bind( event, self.onPress )
				
				self.subSizer.Add( b, ( ( key - 1 ) / self.numberOfColumns[ 0 ], ( key - 1 ) % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )			
                for number in range( self.numberOfRows[ 0 ] ):
                    self.subSizer.AddGrowableRow( number )
                for number in range( self.numberOfColumns[ 0 ] ):
                    self.subSizer.AddGrowableCol( number )
		
		self. mainSizer.Add( self.subSizer, proportion = 1, flag = wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.TOP | wx.RIGHT, border = self.xBorder )
		self.SetSizer( self. mainSizer )
                    
	#-------------------------------------------------------------------------
	def initializeTimer(self):
		self.stoper = wx.Timer( self )
		self.Bind( wx.EVT_TIMER , self.timerUpdate , self.stoper )

		if self.control != 'tracker':
			self.stoper.Start( self.timeGap )
	
	#----------------------