#    Jools -- a graphical puzzle game in the Tetris tradition
#    
#    Copyright (C) 2002-2003 Paul Pelzl
#
#    This program 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 2 of the License, or
#    (at your option) any later version.
#
#    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 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
#

# options.py
#
# provide an options menu
#

import os, pickle
from initialize import *
from globals import *


# convert from slider position to scalar volume multiplier in range [0.0, 2.0]
def posToMult(pos):
   return (pos * 2.0 / 500.0)

# convert from volume multiplier to slider position
def multToPos(mult):
   return (mult * 500.0 / 2.0)


# enable and disable sound effects
def toggleSound(megaOnImage, megaOffImage, megaRect):
   if audio.soundEnabled == 1:
      audio.soundEnabled = 0
      screen.blit(megaOffImage, megaRect)
      pygame.display.flip()
   elif audio.Capable:
      audio.soundEnabled = 1
      screen.blit(megaOnImage, megaRect)
      pygame.display.flip()

# enable and disable music
def toggleMusic(notesOnImage, notesOffImage, notesRect):
   if audio.musicEnabled == 1:
      audio.musicEnabled = 0
      screen.blit(notesOffImage, notesRect)
      pygame.display.flip()
      pygame.mixer.music.stop()
   elif audio.Capable:
      audio.musicEnabled = 1
      screen.blit(notesOnImage, notesRect)
      pygame.display.flip()
      try:
         pygame.mixer.music.play(-1)
      except:
         print "Warning: no music loaded."


def setSoundVolume(mult):
   audio.soundMultiplier = mult
   point1.setVolume(mult)
   point2.setVolume(mult)
   point3.setVolume(mult)
   point4.setVolume(mult)
   point5.setVolume(mult)
   point6.setVolume(mult)
   click.setVolume(mult)
   buzz.setVolume(mult)
   levelup.setVolume(mult)

def setMusicVolume(mult):
   audio.musicMultiplier = mult
   if audio.Capable:
      pygame.mixer.music.set_volume(TITLE_BASE_VOL*mult)



# inform the user that there are no options because audio is
# not enabled
def showNoAudio():
   errorFont = pygame.font.Font("fonts/detonate.ttf", 25)
   text1 = errorFont.render("Jools was unable to initialize sound.", 1, (180,0,0), (1,1,1))
   text2 = errorFont.render("Audio is disabled.", 1, (180,0,0), (1,1,1))
   clickText = highScoreFont2.render("(Click to Continue)", 1, (180, 180, 180), (1, 1, 1) )

   text1Rect = text1.get_rect()
   text2Rect = text2.get_rect()
   clickRect = clickText.get_rect()
   screen.blit(text1, ((SCREENW-text1Rect.width)/2, 200))
   screen.blit(text2, ((SCREENW-text2Rect.width)/2, 200+text1Rect.height+20))
   screen.blit(clickText, ((SCREENW-clickRect.width)/2, SCREENH-10-clickRect.height))

   pygame.display.flip()


   # Mouse button must be released, then pressed, then released again.
   pygame.event.pump()
   clickable = 0
   oldButtonPressed = 0
   while 1:
      if clickable:
         if oldButtonPressed:
            if not pygame.mouse.get_pressed()[0]:
               # center the logo again
               screen.blit(logoEraser, (0,0))
               screen.blit(logoImage, ((SCREENW-logoRect.width)/2, 0))
               break
         elif pygame.mouse.get_pressed()[0]:
            oldButtonPressed = 1

      else:
         if not pygame.mouse.get_pressed()[0]:
            clickable = 1

      pygame.event.pump()
      if pygame.event.wait().type == QUIT:
         pygame.quit()
         sys.exit("Exiting Jools...")



# Load the options from disk.
def loadOptions():
   dummyFile = "~/.jools/options"
   optionsFile = os.path.expanduser(dummyFile)
   # catch for OS's that don't implement $HOME
   if optionsFile == dummyFile:
      optionsFile = ".jools/options"
   optionsFile = os.path.normpath(optionsFile)

   options = [VERSION, []]
   # Check for existence of the jools high options file
   if os.path.exists(optionsFile):
      try:
         f = open(optionsFile, "r")
         options = pickle.load(f)
         f.close()
      except:
         options = [VERSION, []]
      # If the options file is from a previous jools version, wipe it.
      if options[0] != VERSION:
         options = [VERSION, []]

   return (options[1])



# Save the options to disk
def saveOptions():
   optionsList = [audio.soundEnabled, audio.musicEnabled, 
      audio.soundMultiplier, audio.musicMultiplier, audio.soundSet]

   dummyFile = "~/.jools/options"
   optionsFile = os.path.expanduser(dummyFile)
   # catch for OS's that don't implement $HOME
   if optionsFile == dummyFile:
      optionsFile = ".jools/options"
   optionsFile = os.path.normpath(optionsFile)

   dummyDir = "~/.jools"
   optionsDir = os.path.expanduser(dummyDir)
   # catch for OS's that don't implement $HOME
   if optionsDir == dummyDir:
      optionsDir = ".jools"
   optionsDir = os.path.normpath(optionsDir)

   # Check for existence of the directory
   if not os.path.isdir(optionsDir):
      os.mkdir(optionsDir)
   try:
      f = open(optionsFile, "w")
      try:
         pickle.dump([VERSION, optionsList], f)
      except:
         print "Error: Unable to serialize options file."
      f.close()
   except IOError:
      print "Error: Unable to open options file for writing."


def switchSoundSet():
   point1.switchSet(audio.soundSet)
   point2.switchSet(audio.soundSet)
   point3.switchSet(audio.soundSet)
   point4.switchSet(audio.soundSet)
   point5.switchSet(audio.soundSet)
   point6.switchSet(audio.soundSet)
   click.switchSet(audio.soundSet)
   buzz.switchSet(audio.soundSet)
   levelup.switchSet(audio.soundSet)
   point1.setVolume(audio.soundMultiplier)
   point2.setVolume(audio.soundMultiplier)
   point3.setVolume(audio.soundMultiplier)
   point4.setVolume(audio.soundMultiplier)
   point5.setVolume(audio.soundMultiplier)
   point6.setVolume(audio.soundMultiplier)
   click.setVolume(audio.soundMultiplier)
   buzz.setVolume(audio.soundMultiplier)
   levelup.setVolume(audio.soundMultiplier)


def showOptions():
   spacer = 100
   musicScaleY = 150
   soundScaleY = 250
   screen.blit(background, (0,100), (0,100,640,380))   
   testButtonIsOn = 0
   backButtonIsOn = 0

   if not audio.Capable:
      showNoAudio()
      return

#   titleText = highScoreTitleFont.render("Audio Options", 1, (180, 180, 180), (1, 1, 1) )
#   screen.blit(titleText, (250, 80))

   musicScaleRect      = pygame.Rect(scaleRect)
   musicScaleRect.left = spacer
   musicScaleRect.top  = musicScaleY
   soundScaleRect      = pygame.Rect(scaleRect)
   soundScaleRect.left = spacer
   soundScaleRect.top  = soundScaleY

   screen.blit(scaleImage, musicScaleRect)
   screen.blit(scaleImage, soundScaleRect)

   musicSliderRect      = pygame.Rect(sliderRect)
   musicSliderRect.left = spacer-(sliderRect.width/2) + multToPos(audio.musicMultiplier)
   musicSliderRect.top  = musicScaleY - 10
   soundSliderRect      = pygame.Rect(sliderRect)
   soundSliderRect.left = spacer-(sliderRect.width/2) + multToPos(audio.soundMultiplier)
   soundSliderRect.top  = soundScaleY - 10
   sliderEraser = pygame.Surface((musicSliderRect.width, musicSliderRect.height))
   sliderEraser.fill((1,1,1))

   # the rects used for mouse pointer detection are a bit bigger than
   # the size of the scale images, since the slider is taller than
   # the image height
   musicScaleRect2        = pygame.Rect(musicScaleRect)
   musicScaleRect2.height = musicSliderRect.height
   musicScaleRect2.top    = musicSliderRect.top
   soundScaleRect2        = pygame.Rect(soundScaleRect)
   soundScaleRect2.height = soundSliderRect.height
   soundScaleRect2.top    = soundSliderRect.top

   screen.blit(sliderImage, musicSliderRect)
   screen.blit(sliderImage, soundSliderRect)

   notesRect      = pygame.Rect(notesOnRect)
   notesRect.left = 30
   notesRect.top  = musicScaleY - 5
   megaRect       = pygame.Rect(megaOnRect)
   megaRect.left  = 10
   megaRect.top   = soundScaleY - 5
   
   if audio.musicEnabled:
      screen.blit(notesOnImage, notesRect)
   else:
      screen.blit(notesOffImage, notesRect)
   if audio.soundEnabled:
      screen.blit(megaOnImage, megaRect)
   else:
      screen.blit(megaOffImage, megaRect)


   soundSetFont = pygame.font.Font("fonts/detonate.ttf", 25)
   soundSetText = soundSetFont.render("sound FX set: ", 1, (190,0,210), (1,1,1))
   soundSetNum  = soundSetFont.render(str(audio.soundSet), 1, (190,0,210), (1,1,1))
   soundSetNumEraser          = soundSetFont.render(str(99), 1, (1,1,1), (1,1,1))
   soundSetNumEraserRect      = soundSetNumEraser.get_rect()
   soundSetNumEraserRect.left = 400 + soundSetText.get_rect().width
   soundSetNumEraserRect.top  = soundScaleY + 80

   screen.blit(soundSetText, (400, soundScaleY + 80))
   screen.blit(soundSetNum, (400 + soundSetText.get_rect().width, soundScaleY + 80))

   arrowUpRect.left = (400 + soundSetText.get_rect().width + 
      soundSetNumEraserRect.width)
   arrowUpRect.top = soundScaleY + 75
   arrowDownRect.left = (400 + soundSetText.get_rect().width + 
      soundSetNumEraserRect.width)
   arrowDownRect.top = soundScaleY + 95
   screen.blit(arrowUpImage, arrowUpRect)
   screen.blit(arrowDownImage, arrowDownRect)

   testRect.left = 480
   testRect.top  = soundScaleY + 130
   screen.blit(testButton, testRect)

   backRect.left = 10
   backRect.top  = SCREENH-10-backRect.height
   screen.blit(backButton, backRect)

   pygame.display.flip()


   oldMousePressed = pygame.mouse.get_pressed()[0]
   oldKeyTuple = pygame.key.get_pressed()
   while 1:
      mousePressed = pygame.mouse.get_pressed()[0]
      mousePos = pygame.mouse.get_pos()
      keyTuple = pygame.key.get_pressed()
      
      # check whether sound support is being toggled
      if not oldMousePressed and mousePressed:
         if notesRect.collidepoint(mousePos[0], mousePos[1]):
            toggleMusic(notesOnImage, notesOffImage, notesRect)
         elif megaRect.collidepoint(mousePos[0], mousePos[1]):
            toggleSound(megaOnImage, megaOffImage, megaRect)
         elif testRect.collidepoint(mousePos[0], mousePos[1]):
            testButtonIsOn = 1
            screen.blit(testButtonOn, testRect)
            pygame.display.update(testRect)
            point1.play()
         elif arrowUpRect.collidepoint(mousePos[0], mousePos[1]):
            screen.blit(soundSetNumEraser, soundSetNumEraserRect)
            audio.soundSet += 1
            if audio.soundSet > SOUND_SET_MAX:
               audio.soundSet = 0
            soundSetNum = soundSetFont.render(str(audio.soundSet), 1, (190,0,210), (1,1,1))
            screen.blit(soundSetNum, (400 + soundSetText.get_rect().width, soundScaleY + 80))
            pygame.display.update([soundSetNumEraserRect])
            switchSoundSet()
         elif arrowDownRect.collidepoint(mousePos[0], mousePos[1]):
            screen.blit(soundSetNumEraser, soundSetNumEraserRect)
            audio.soundSet -= 1
            if audio.soundSet < 0:
               audio.soundSet = SOUND_SET_MAX
            soundSetNum = soundSetFont.render(str(audio.soundSet), 1, (190,0,210), (1,1,1))
            screen.blit(soundSetNum, (400 + soundSetText.get_rect().width, soundScaleY + 80))
            pygame.display.update([soundSetNumEraserRect])
            switchSoundSet()
      elif mousePressed:
         if musicScaleRect2.collidepoint(mousePos[0], mousePos[1]):
            screen.blit(sliderEraser, musicSliderRect)
            oldRect = pygame.Rect(musicSliderRect)
            musicSliderRect.left = mousePos[0] - (sliderRect.width/2)
            screen.blit(scaleImage, musicScaleRect)
            screen.blit(sliderImage, musicSliderRect)
            pygame.display.update([oldRect, musicSliderRect])
            mult = posToMult(mousePos[0] - musicScaleRect.left)
            setMusicVolume(mult)
         elif soundScaleRect2.collidepoint(mousePos[0], mousePos[1]):
            screen.blit(sliderEraser, soundSliderRect)
            oldRect = pygame.Rect(soundSliderRect)
            soundSliderRect.left = mousePos[0] - (sliderRect.width/2)
            screen.blit(scaleImage, soundScaleRect)
            screen.blit(sliderImage, soundSliderRect)
            pygame.display.update([oldRect, soundSliderRect])
            mult = posToMult(mousePos[0] - soundScaleRect.left)
            setSoundVolume(mult)
         elif backRect.collidepoint(mousePos[0], mousePos[1]):
            backButtonIsOn = 1
            screen.blit(backButtonOn, backRect)
            pygame.display.update(backRect)
      else:
         if oldMousePressed and backRect.collidepoint(mousePos[0], mousePos[1]):
            saveOptions()
            return

      if backButtonIsOn and (not mousePressed or not
            backRect.collidepoint(mousePos[0], mousePos[1])):
         backButtonIsOn = 0
         screen.blit(backButton, backRect)
         pygame.display.update(backRect)
      if testButtonIsOn and (not mousePressed or not
            testRect.collidepoint(mousePos[0], mousePos[1])):
         testButtonIsOn = 0
         screen.blit(testButton, testRect)
         pygame.display.update(testRect)
      

      if keyTuple[K_m] and not oldKeyTuple[K_m]:
         toggleMusic(notesOnImage, notesOffImage, notesRect)
      elif keyTuple[K_s] and not oldKeyTuple[K_s]:
         toggleSound(megaOnImage, megaOffImage, megaRect)

      oldMousePressed = mousePressed
      oldKeyTuple     = keyTuple

      pygame.event.pump()
      if pygame.event.wait().type == QUIT:
         pygame.quit()
         sys.exit("Exiting Jools...")



# arch-tag: options menu

