#
#  Input.py

import k

from Krank  import *
from Sprite import *

#-----------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------

class Input:
    
    #-------------------------------------------------------------------------------------------
    def __init__(self):
        
        k.input = self
        
        pygame.mouse.set_cursor(*pygame.cursors.diamond)
         
        self.exit = False
        self.pause = False
        
        # target pos
        self.targetpos = k.world.rect.center
        
        # joystick 

        pygame.joystick.init()
                
        self.joystick = None # the first joystick if present
        self.joyaxes  = []   # current axes values
        self.relaxes  = []   # joystick delta
        self.numaxes  = 0    # number of joystick axes
        self.minaxes  = 0.2  # joystick delta threshold
                
        if pygame.joystick.get_init() and pygame.joystick.get_count():
            self.joystick = pygame.joystick.Joystick(0)
            if self.joystick:
                self.joystick.init()
                if self.joystick.get_init():
                    self.numaxes = min(2, self.joystick.get_numaxes())
                    self.joyaxes = [0.0] * self.numaxes
                    self.relaxes = [0.0] * self.numaxes
                    #self.handleMouse()
                else:
                    log("joystick init failed")
                    self.joystick = None

    #-------------------------------------------------------------------------------------------
    def onExit (self):
        self.exit = True
                    
    #-------------------------------------------------------------------------------------------
    def onFrame (self, delta):
        
        self.handleEvents ()
        self.handleMouse ()
        
    #-------------------------------------------------------------------------------------------
    def handleEvents (self):
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            # ---------------------------------------------------------------------- KEYS 
            elif event.type == pygame.KEYDOWN:
                # ------------------------------------------------------------------ pause
                if event.key == 32:
                    self.pause = not self.pause
                else:
                    if self.pause: self.pause = False
                # ------------------------------------------------------------------ exit
                if event.key == 113 and event.mod == pygame.KMOD_LMETA:
                    self.onExit()
                    return
                # ------------------------------------------------------------------ menu
                elif event.key == 27:
                    if event.mod == pygame.KMOD_LSHIFT:
                        log('quick exit (shift escape)', event, log='input')
                        self.onExit()
                        return
                    log('menu exit (escape)', event, log='input')
                    if k.level.name <> "menu":
                        k.level.menuExit("menu")
                    else:
                        self.onExit()
                        return
                # ------------------------------------------------------------------ levels
                elif event.key == 275: # right
                    pygame.event.clear()
                    if k.debug and event.mod == pygame.KMOD_LMETA:
                        k.score, k.level.time = sys.maxint, sys.maxint
                        k.config.score(k.level.number)
                    else:
                        k.config.abort()
                    k.level.next()
                elif event.key == 276: # left
                    pygame.event.clear()
                    k.config.abort()
                    k.level.previous()
                elif event.key == 105: # i
                    if k.debug:
                        k.level.saveIcon()
                elif event.key == 114: # r
                    k.config.abort()
                    k.level.restart()
                elif event.key == 115: # s
                    k.level.saveScreenshot()
                elif event.key in [49, 50, 51]:
                    if k.debug:
                        k.config.stage = event.key-48
                        k.score, k.level.time = sys.maxint, sys.maxint
                        k.config.score(k.level.number)
                        k.level.restart()
                # ------------------------------------------------------------------ volume
                elif event.key == 280 or event.key == 281: # page up/page down
                    delta = event.key == 280 and 1 or -1
                    if event.mod & pygame.KMOD_ALT:
                        k.sound.setSoundVolume(k.sound.getSoundVolume() + delta*0.1)
                    else:
                        k.sound.setMusicVolume(k.sound.getMusicVolume() + delta*0.1)
                    k.config.save()
                # ------------------------------------------------------------------ misc
                else:
                    log(event, log='input')
                    pass
            # ---------------------------------------------------------------------- JOYSTICK
            elif event.type == pygame.JOYBUTTONUP:
                # ------------------------------------------------------------------ exit
                if event.button == 0:
                    # bug in pygame? get's triggered sometimes on OS X
#                    log("JOY BUTTON UP", log='input')
#                    if k.level.name <> "menu":
#                        log('menu exit (joy button)', log='input')
#                        k.level.menuExit("menu")
                    pass
                # ------------------------------------------------------------------ volume
                elif event.button >= 4 and event.button <= 7: # shoulder buttons
                    delta = event.button <= 5 and -1 or 1
                    if event.button % 2:
                        k.sound.setSoundVolumeIndex(k.sound.getSoundVolumeIndex() + delta)
                        if k.level.name == "menu_sound":
                            k.particles.parts[k.player.tailnum+2:][k.sound.getSoundVolumeIndex()].collision_action()
                    else:
                        k.sound.setMusicVolumeIndex(k.sound.getMusicVolumeIndex() + delta)
                        if k.level.name == "menu_sound":
                            k.particles.parts[k.player.tailnum+8:][k.sound.getMusicVolumeIndex()].collision_action()
                    k.config.save()
                else:
                    log(event)
            elif event.type == pygame.JOYBUTTONDOWN:
                log(event, event.button, log='input')
            # ---------------------------------------------------------------------- USER                
            elif event.type == kNEXT_LEVEL:
                k.sound.removeEndEvent(kNEXT_LEVEL)
                pygame.time.set_timer(kNEXT_LEVEL, 0)
                k.level.next()
            elif event.type == kLOAD_LEVEL:
                k.sound.removeEndEvent(kLOAD_LEVEL)
                pygame.time.set_timer(kLOAD_LEVEL, 0)
                k.level.load()
            elif event.type == kMENU_LEVEL:
                k.sound.removeEndEvent(kMENU_LEVEL)
                pygame.time.set_timer(kMENU_LEVEL, 0)
                k.level.menu()
            else:
#                log(event, log='input')
                pass
           
    #-------------------------------------------------------------------------------------------
    def handleMouse (self):

        mousepos = vector(pygame.mouse.get_pos())
        playerpos = vector(k.player.part.pos)
             
        joymoved = 0
        if self.joystick:   
            for i in range(self.numaxes):
                axis = self.joystick.get_axis(i)
                self.relaxes[i] = axis - self.joyaxes[i]
                self.joyaxes[i] = axis
                if abs(self.joyaxes[i]) > self.minaxes:
                    joymoved = 1
            
        if joymoved:
            targetDistance = max(abs(self.joyaxes[0]), abs(self.joyaxes[1])) * k.player.maxTargetDistance
            self.targetpos = playerpos + vector(self.joyaxes).norm() * targetDistance
            self.targetpos.x = min(max(self.targetpos.x, 0), k.world.rect.width)
            self.targetpos.y = min(max(self.targetpos.y, 0), k.world.rect.height)
            pygame.mouse.set_pos(self.targetpos)
        else:
            playerToMouse = playerpos.to(mousepos)
#            log(playerToMouse)
            playerToMouseDistance = playerToMouse.length()
            playerToMouseFactor = min(playerToMouseDistance/1, k.player.maxTargetDistance)
            targetDistance = min(playerToMouseDistance, playerToMouseFactor)
            self.targetpos = playerpos + playerToMouse.norm() * targetDistance

            
            