'''
Created on 12 nov. 2009

@author: Samuel Benveniste
'''

import os
import sys
import subprocess

import pygame
import pygame.midi
import pickle

from pygame.locals import *

from pgu import gui as pguGui

from PlayingScreen import PlayingScreen
from SongPlayingScreen import SongPlayingScreen
from InstrumentChoice import InstrumentChoice
from instruments.Instrument import Instrument
from cursor.WarpingCursor import *
from controllers.Wiimote import Wiimote
from logging.Log import Log
from songs.Song import Song,loadSong
from constants import *
from MINWiiDialog import MINWiiDialog

class PGUConfiguration(pguGui.Desktop):
    '''
    classdocs
    '''


    def __init__(self,window):
        '''
        Constructor
        '''
        pguGui.Desktop.__init__(self)
        self.extendedScale = False
        self.cascade = False
        self.song = None
        self.scale = scaleDict["majorScale"]
        self.log = None
        self.done = False
        self.easyMode = True
        self.mode = 0
        self.activeWiimotes = [False for i in range(4)]
        self.alwaysDown = False
        
        self.file = None
        #fileName is the path for the log file
        self.fileName = fileName
        self.titleFont = pygame.font.Font(None,100)
        self.font = pygame.font.Font(None,70)
        self.spaceSize = (100,100)
        
        self.browseButton = pguGui.Button(self.createLabel("Choisir..."))
        self.browseButton.connect(pguGui.CLICK, self.open_file_browser, None)
        
        self.songSwitch = pguGui.Switch(False)
        
        self.modeSelect = pguGui.Select()
        for key in modeDict.keys() :
            self.modeSelect.add(self.createLabel(reversedReadabilityDict[key]),key)
        self.modeSelect.connect(pguGui.CHANGE,self.modeSelectChanged,None)
        
        self.activeWiimoteSwitches = [pguGui.Switch(False) for i in range(4)]
        for i in range(len(self.activeWiimoteSwitches)) :
            self.activeWiimoteSwitches[i].connect(pguGui.CHANGE,self.activeWiimoteSwitchesChanged,i)
        
        self.goButton = pguGui.Button(self.createLabel("Go"))
        self.goButton.connect(pguGui.CLICK,self.goButtonClicked,None)
        
        self.quitButton = pguGui.Button(self.createLabel("Fin"))
        self.quitButton.connect(pguGui.CLICK,self.quitButtonClicked,None)
        
        self.connect(pguGui.QUIT,self.quit,None)
        
        self.window = window
        
        ##The table code is entered much like HTML.
        ##::
        
        self.mainTable = pguGui.Table()
        
        self.fillMainTable()
                
#        self.mainTable.tr()
#        self.mainTable.td(self.createLabel("MINWii",self.titleFont),colspan = 4)
        
        self.run(self.mainTable)
        
    def open_file_browser(self,data=None):
        d = MINWiiDialog(font = self.font,width = 800, height = 600,path = "../songs/smwis")
        d.connect(pguGui.CHANGE, self.handle_file_browser_closed, d)
        d.open()
    

    def handle_file_browser_closed(self,dlg):
        if dlg.value:
            if os.path.isfile(dlg.value):
                self.file = dlg.value
                self.song = loadSong(self.file)
                key = os.path.basename(self.file)[:-5]
                if key in reversedReadabilityDict :                     
                    label = self.createLabel(reversedReadabilityDict[key])
                else :
                    label = self.createLabel(key)
                self.browseButton = pguGui.Button(label)
                self.browseButton.connect(pguGui.CLICK, self.open_file_browser, None)
                if not self.songSwitch.value :
                    self.songSwitch.click()
                self.mainTable.clear()
                self.fillMainTable()
                
    def fillMainTable(self):
        
        self.mainTable.tr()
        self.mainTable.td(pguGui.Spacer(*self.spaceSize))
        
        self.mainTable.tr()
        self.mainTable.td(self.createLabel("Chanson :"))
        self.mainTable.td(self.browseButton,colspan=2)
        self.mainTable.td(self.songSwitch)
        
        self.mainTable.tr()
        self.mainTable.td(pguGui.Spacer(*self.spaceSize))
        
        self.mainTable.tr()
        self.mainTable.td(self.createLabel("Niveau :"))
        self.mainTable.td(self.modeSelect,colspan=3)
        
        self.mainTable.tr()
        self.mainTable.td(pguGui.Spacer(*self.spaceSize))
        
        self.mainTable.tr()
        self.mainTable.td(self.createLabel("Joueurs :", self.font))
        playerTable = pguGui.Table()
        for i in range(len(self.activeWiimoteSwitches)):
            playerTable.td(self.createLabel(" " + str(i+1)+" ", self.font))
            playerTable.td(self.activeWiimoteSwitches[i])
        self.mainTable.td(playerTable,colspan = 3)
        
        self.mainTable.tr()
        self.mainTable.td(pguGui.Spacer(*self.spaceSize))
        
        self.mainTable.tr()
        self.mainTable.td(self.goButton)
        self.mainTable.td(self.quitButton,colspan=3)        
        
        self.mainTable.tr()
        self.mainTable.td(pguGui.Spacer(500,500))        
                           
    def createLabel(self,text,font = None):
        if font == None :
            font = self.font
        w,h = self.font.size(text)
        label = pguGui.Label(text,width=w,height=h,font = font)
        return(label)
    
    def songSelectChanged(self,data=None):
        self.song = songDict[self.songSelect.value]
        
    def activeWiimoteSwitchesChanged(self,data = None):
        if self.activeWiimoteSwitches[data].value :
            for i in range(len(self.activeWiimoteSwitches)) :
                if self.activeWiimoteSwitches[i].value and data != i :
                    self.activeWiimoteSwitches[i].click()                
        for i in range(len(self.activeWiimoteSwitches)) :
            self.activeWiimotes[i] = self.activeWiimoteSwitches[i].value
        
    def modeSelectChanged(self,data = None):
        self.mode = modeDict[self.modeSelect.value]
        
    def hasActiveWiimote(self):
        hasActive = False
        for i in self.activeWiimotes:
            if i :
                hasActive = True
        return(hasActive)
    
    def quitButtonClicked(self,data = None):
        self.done = True
        print 'puti'
        for isActive in self.activeWiimotes :
            print isActive
        self.quit()
    
    def goButtonClicked(self,data = None):
        pygame.font.init()
        
        if not self.hasActiveWiimote():
            self.activeWiimotes[0] = True
        pygame.midi.init()
        instruments = [Instrument(self.scale, i + 1, "".join(["../instruments/instrumentImages/", instrumentImagePathList[i], ".jpg"]), octaves[i]) for i in range(9)]
        
        joys = [[id,pygame.joystick.Joystick(id).get_name()] for id in range(pygame.joystick.get_count())]
        for joy in joys:
            print joy[1]
            if joy[1] in joyNames:
                print "On"
                pygame.joystick.Joystick(joy[0]).init()
            else :
                print "off" 
        
        ports = [pygame.midi.get_device_info(id)[1] for id in range(pygame.midi.get_count())]
        portOffset = ports.index(portNames[0])
        print(portOffset)
        
        screen = pygame.display.get_surface()
        clock = pygame.time.Clock()        
        cursorImages=[['../cursor/cursorImages/black/10.png'],['../cursor/cursorImages/red/10.png'],['../cursor/cursorImages/blue/10.png'],['../cursor/cursorImages/green/10.png']]
        durations = [75 for i in range(len(cursorImages[0]))]
        
        wiimoteCount = 4
        cursors = [WarpingCursor(None, cursorImages[i], durations, (300 * i, 300 * i),flashImage = '../cursor/cursorImages/black/flash.png' ) for i in range(wiimoteCount)]
        wiimotes = [Wiimote(i, i + portOffset, None, None, cursors[i]) for i in range(wiimoteCount)]
        
        if self.song != None and self.songSwitch.value :
            
            if self.mode == 0 :
                self.extendedScale = self.song.requiresExtendedScale
                self.cascade = True
                self.easyMode = True
                self.alwaysDown = True
            elif self.mode == 1 :
                self.extendedScale = self.song.requiresExtendedScale
                self.cascade = True
                self.easyMode = True
            elif self.mode == 2:
                self.extendedScale = self.song.requiresExtendedScale
                self.cascade = False
                self.easyMode = True
            elif self.mode == 3:
                self.extendedScale = True
                self.cascade = False
                self.easyMode = False
                
            choice = InstrumentChoice(instruments, wiimotes, self.window, screen, clock, joys, portOffset,self.activeWiimotes, scaleFactor = songScaleFactor)
            play = SongPlayingScreen(choice, self.song,self.cascade, self.extendedScale,self.easyMode,self.alwaysDown)
        
        else:
            
            if self.mode == 0 :
                self.extendedScale = False
                self.cascade = False
            elif self.mode == 1 :
                self.extendedScale = True
                self.cascade = False
            elif self.mode == 2:
                self.extendedScale = False
                self.cascade = True
            elif self.mode == 3:
                self.extendedScale = True
                self.cascade = True
                
            choice = InstrumentChoice(instruments, wiimotes, self.window, screen, clock, joys, portOffset,self.activeWiimotes)
            play = PlayingScreen(choice, None,self.cascade, self.extendedScale)            
                
        while play.backToInstrumentChoice == True :
            
            for wiimote in wiimotes:
                del wiimote.port
                
            wiimotes = [Wiimote(i, i + portOffset, None, None, cursors[i]) for i in range(wiimoteCount)]
            previousEventLog = choice.eventLog

            if self.song != None :
                choice = InstrumentChoice(instruments, wiimotes, self.window, screen, clock, joys, portOffset, self.activeWiimotes,eventLog = previousEventLog, replay = False, scaleFactor = songScaleFactor)
                play = SongPlayingScreen(choice, self.song, False, self.extendedScale,self.easyMode)
            else:
                choice = InstrumentChoice(instruments, wiimotes, self.window, screen, clock, joys, portOffset,self.activeWiimotes, eventLog = previousEventLog, replay = False)
                play = PlayingScreen(choice, None, self.cascade, self.extendedScale)
                               
        for wiimote in wiimotes:
                del wiimote.port
        
        i = 1        
        filePath = "".join([self.fileName,str(i),".mwi"])        
        while os.path.exists(filePath):
            i += 1
            filePath = "".join([self.fileName,str(i),".mwi"])            
        
        f = file(filePath, 'w')
        self.log = Log(play.eventLog,self.scale,self.extendedScale,self.cascade,self.song,self.mode,self.activeWiimotes)
        pickler = pickle.Pickler(f)
        pickler.dump(self.log)
        
        f.close()
        
        pygame.midi.quit()
        
        self.repaint()
        
if __name__ == "__main__" :
    pygame.init()
    modeResolution = (1024,768)
    window = pygame.display.set_mode(modeResolution,pygame.FULLSCREEN)
    pgu = PGUConfiguration(window)
    pygame.quit()   
        
        
        
        