#
###
# Application: Pycadia
# File:        pycadia_prefs.py
# Description: Pycadia GUI Preferences dialog code
# Copyright (c) 2002-2003   Andy Balcombe <http://www.anti-particle.com>
###
#
# 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 Library 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.
#

import pygame

from glade2 import *
import config
from pyg_keys import get_key_press, get_joystick_action, get_joystick_list

class Prefs(LoadGlade2):
    """
    The pycadia preferences gui class
    """
    def __init__(self, sFilename, sWindowName, gtkParent):
        #init window
        LoadGlade2.__init__(self, sFilename, sWindowName)
        self.winPrefs.set_transient_for(gtkParent)
        self.winPrefs.set_destroy_with_parent(1)
        self.winPrefs.show()
        #init screen res dict
        self.dScreenSize = {1:'640x480', 2:'800x600', 3:'1024x768', 4:'1280x1024', 5:'1024x480'}
        #get list of joysticks
        self.dJoysticks = get_joystick_list()
        self.cboJoystick1.set_popdown_strings(self.dJoysticks.values())
        self.cboJoystick2.set_popdown_strings(self.dJoysticks.values())
        #get config
        self.sCfgFile, self.cfg = config.PycadiaConfig()
        self.get_settings()
        
    def get_settings(self):
        """get config from file"""
        #joystick axes
        dAxis = {0:'x', 1:'y', 2:'z'}
        dAxisVal = {-1:'-', 1:'+'}
        #get player names
        self.entP1_Name.set_text(self.cfg.get('player1', 'name'))
        self.entP2_Name.set_text(self.cfg.get('player2', 'name'))
        #get joystick names
        self.cbeJoystick1.set_text(self.dJoysticks.get(self.cfg.getint('player1', 'joy_id')))
        self.cbeJoystick2.set_text(self.dJoysticks.get(self.cfg.getint('player2', 'joy_id')))
        #get controls
        lKeyControls = ['key_left', 'key_right', 'key_thrust', 'key_fire', 'key_hyper']
        lKeyButtons = ['btnP~K_Left', 'btnP~K_Right', 'btnP~K_Thrust', 'btnP~K_Fire', 'btnP~K_Hyper']
        lJoyControls = ['joy_left', 'joy_right', 'joy_thrust', 'joy_fire', 'joy_hyper']
        lJoyButtons = ['btnP~J_Left', 'btnP~J_Right', 'btnP~J_Thrust', 'btnP~J_Fire', 'btnP~J_Hyper'] 
        #for each player
        for iPlayer in [1,2]:
            #for each control
            for i in range(5):
                #get key char & button & set label
                s = pygame.key.name(self.cfg.getint('player%s' % (iPlayer), lKeyControls[i]))
                btn = lKeyButtons[i].replace('~', str(iPlayer))
                exec('self.%s.set_label(s)' % (btn))
                #get joy char & button & set label
                l = eval(self.cfg.get('player%s' % (iPlayer), lJoyControls[i]))
                if l[0] == 'axis':
                    #joystick axis
                    s = '%s %s%s' % (l[0], dAxisVal.get(l[2]), dAxis.get(l[1]))
                else:
                    #joystick button
                    s = '%s %s' % (l[0], l[1])
                btn = lJoyButtons[i].replace('~', str(iPlayer))
                exec('self.%s.set_label(s)' % (btn))
        #get spacewarpy options
        self.hscSW_PlayerLives.set_value(float(self.cfg.get('spacewarpy', 'player_lives')))
        self.hscSW_Gravity.set_value(float(self.cfg.get('spacewarpy', 'gravity')))
        self.hscSW_ShotLife.set_value(float(self.cfg.get('spacewarpy', 'shot_life')))
        self.hscSW_PlayerShots.set_value(float(self.cfg.get('spacewarpy', 'max_shots')))
        self.hscSW_AsteroidDestroy.set_value(float(self.cfg.get('spacewarpy', 'asteroid_destroy')))
        self.hscSW_AsteroidDelay.set_value(float(self.cfg.get('spacewarpy', 'asteroid_delay')))
        #get vektoroids options
        self.hscPS_PlayerLives.set_value(float(self.cfg.get('vektoroids', 'player_lives')))
        self.hscPS_AsteroidDestroy.set_value(float(self.cfg.get('vektoroids', 'asteroid_destroy')))
        self.hscPS_ShotLife.set_value(float(self.cfg.get('vektoroids', 'shot_life')))
        self.hscPS_PlayerShots.set_value(float(self.cfg.get('vektoroids', 'max_shots')))
        self.hscPS_AsteroidWave.set_value(float(self.cfg.get('vektoroids', 'asteroid_wave')))
        #display tab
        self.iScreenSizePos = 0
        self.hscScreenSize.set_value(self.cfg.getint('display', 'screensize_pos'))
        self.chkFullScreen.set_active(self.cfg.getint('display', 'fullscreen'))
        self.hscTargetFPS.set_value(self.cfg.getint('display', 'target_fps'))
        #gui
        self.nbkPrefs.set_current_page(self.cfg.getint('pycadia', 'tab_position'))

    def save_settings(self):
        """save config to file"""
        #set player names
        self.cfg.set('player1', 'name', self.entP1_Name.get_text())
        self.cfg.set('player2', 'name', self.entP2_Name.get_text())
        #set joystick id's
        self.cfg.set('player1', 'joy_id', self.p1_joy_id)
        self.cfg.set('player2', 'joy_id', self.p2_joy_id)
        #set spacewarpy options
        self.cfg.set('spacewarpy', 'player_lives', int(self.hscSW_PlayerLives.get_value()))
        self.cfg.set('spacewarpy', 'gravity', self.hscSW_Gravity.get_value())
        self.cfg.set('spacewarpy', 'shot_life', self.hscSW_ShotLife.get_value())
        self.cfg.set('spacewarpy', 'max_shots', int(self.hscSW_PlayerShots.get_value()))
        self.cfg.set('spacewarpy', 'asteroid_destroy', int(self.hscSW_AsteroidDestroy.get_value()))
        self.cfg.set('spacewarpy', 'asteroid_delay', int(self.hscSW_AsteroidDelay.get_value())     )  
        #set vektoroids options
        self.cfg.set('vektoroids', 'player_lives', int(self.hscPS_PlayerLives.get_value()))
        self.cfg.set('vektoroids', 'asteroid_destroy', int(self.hscPS_AsteroidDestroy.get_value()))
        self.cfg.set('vektoroids', 'shot_life', self.hscPS_ShotLife.get_value())
        self.cfg.set('vektoroids', 'max_shots', int(self.hscPS_PlayerShots.get_value()))
        self.cfg.set('vektoroids', 'asteroid_wave', int(self.hscPS_AsteroidWave.get_value()))
        #set display options
        self.cfg.set('display', 'target_fps', int(self.hscTargetFPS.get_value()))
        #gui
        self.cfg.set('pycadia', 'tab_position', int(self.nbkPrefs.get_current_page()))
        #write details to file
        f = open(self.sCfgFile, 'w')
        self.cfg.write(f)
        f.close()

    def on_btnOK_clicked(self, *args):
        """ok clicked"""
        self.save_settings()
        self.on_winPrefs_destroy()
        
    def on_btnCancel_clicked(self, *args):
        """cancel preferences"""
        self.on_winPrefs_destroy()

    #set keys
    def on_btnSetKey_clicked(self, btn):
        """get key press"""
        #get key press
        sKey, iKey = get_key_press()
        if sKey != '':
            #set the label
            btn.set_label(sKey)
            #get button name, player number and direction
            sBtn = btn.get_name()
            iPlayer = int(sBtn[4])
            sDir = 'key_' + sBtn[7:].lower()
            #set config file
            self.cfg.set('player%s' % (iPlayer), sDir, iKey)

    def on_btnSetJoy1_clicked(self, btn):
        """get joystick axis / button"""
        #get joystick id
        joystick_id = self.p1_joy_id
        #get button / axis
        joy_button = self.get_joystick(btn, joystick_id)
        
    def on_btnSetJoy2_clicked(self, btn):
        """get joystick axis / button"""
        #get joystick id
        joystick_id = self.p2_joy_id
        #get button / axis
        joy_button = self.get_joystick(btn, joystick_id)
        
    def on_cbeJoystick1_changed(self, gte):
        """player 1 selected joystick changed""" 
        joyname = gte.get_text()
        if joyname != None:
            #for each joy id
            for i, s in self.dJoysticks.items():
                if s == joyname:
                    #set id
                    self.p1_joy_id = i
                    break
        
    def on_cbeJoystick2_changed(self, gte):
        """player 2 selected joystick changed""" 
        joyname = gte.get_text()
        if joyname != None:
            #for each joy id
            for i, s in self.dJoysticks.items():
                if s == joyname:
                    #set id
                    self.p2_joy_id = i
                    break
        
    def on_winPrefs_destroy(self, *args):
        """close preferences window"""
        self.winPrefs.destroy()

    def get_joystick(self, btn, joystick_id):
        """get button / axis"""
        #get button name, player number and direction
        sBtn = btn.get_name()
        iPlayer = int(sBtn[4])
        sDir = 'joy_' + sBtn[7:].lower()
        #get value
        joy_button, joy_axis_id, joy_axis_dir, joy_axis_val = get_joystick_action(joystick_id)
        #button or axis 
        if joy_button >= 0:
            btn.set_label('button %s' % (joy_button))
            sJoy = "['button', %s, 1]" % (joy_button)
        elif joy_axis_id >= 0:
            btn.set_label(joy_axis_dir)
            sJoy = "['axis', %s, %s]" % (joy_axis_id, joy_axis_val)
        #set config file
        self.cfg.set('player%s' % (iPlayer), sDir, sJoy)

    #display tab
    def on_hscScreenSize_value_changed(self, hsc, *args):
        """set screen size"""
        #get value from widget
        iPos = int(hsc.get_value())
        if iPos != self.iScreenSizePos:
            #value has changed
            self.iScreenSizePos = iPos
            sRes = self.dScreenSize.get(iPos)
            self.lblScreenSize.set_text(sRes)
            #get x and y size from label
            x = sRes[:sRes.index('x')]
            y = sRes[sRes.index('x')+1:]
            #set size & pos
            self.cfg.set('display', 'screensize_pos', iPos)
            self.cfg.set('display', 'screensize_x', x)
            self.cfg.set('display', 'screensize_y', y)
        
    def on_chkFullScreen_toggled(self, *args):
        """toggle full screen option"""
        self.cfg.set('display', 'fullscreen', self.chkFullScreen.get_active() == gtk.TRUE)
        