import pygame
import sys

class mainDisplay:
   def __init__ ( self , screen , joystick ):
      # Setup class variables
      self.screen = screen
      self.width = screen.get_width()
      self.height = screen.get_height()
      self.joystick = joystick

      # Draw dividing lines onto the window
      pygame.draw.line ( self.screen , ( 0 , 255 , 0 ) , ( self.width / 2 , 0 ) , ( self.width / 2 , self.height ) , 1 )
      pygame.draw.line ( self.screen , ( 0 , 255 , 0 ) , ( 0 , self.height / 2 ) , ( self.width , self.height / 2 ) , 1 )

      # Initialize the font module to label things
      pygame.font.init()
      self.labelFont = pygame.font.SysFont ( "" , 15 , False , False )

      # Get the number of each type of input from the joystick
      self.axisCount = joystick.get_numaxes()
      self.buttonCount = joystick.get_numbuttons()
      self.ballCount = joystick.get_numballs()
      self.hatCount = joystick.get_numhats()

      # Initialize the plotting functions for each type of input
      self.joyAxes = dict()
      for i in range ( self.axisCount ):
         self.joyAxes [ i ] = 0
      self.plotAxes()

      self.joyButtons = dict()
      for i in range ( self.buttonCount ):
         self.joyButtons [ i ] = False
      self.plotButtons()

      for i in range ( self.hatCount ):
         self.plotHat ( i , ( 0 , 0 ) )

      self.ballLocations = dict()
      for i in range ( self.ballCount ):
         self.ballLocations [ i ] = list()
         self.ballLocations [ i ].append ( 0 )
         self.ballLocations [ i ].append ( 0 )
         self.plotBalls ( i , ( 0 , 0 ) )

   def meter ( self , position , size , label , value ):
      # The meter function plots a value on a horizontal scale
      # Variables:
      # position -- a tuple where the meter should be plotted on screen
      # size -- the width of the meter (height is always 30 pixels)
      # label -- the text to label this meter
      # value -- a float ranging from -1 to 1 to show on the meter (0 is center)

      pygame.draw.rect ( self.screen , ( 0 , 0 , 0 ) , ( position [ 0 ] - 2 , position [ 1 ] , size + 4 , 30 ) , 0 )
      caption = self.labelFont.render ( label , True , ( 0 , 255 , 0 ) )

      self.screen.blit ( caption , position )
      pygame.draw.rect ( self.screen , ( 0 , 255 , 0 ) , ( position [ 0 ] , position [ 1 ] + 14 , size , 2 ) , 0 )
      pointerX = ( size / 2 ) + ( size * ( value / 2 ) ) - 1 + position [ 0 ]
      pygame.draw.rect ( self.screen , ( 0 , 255 , 0 ) , ( pointerX , position [ 1 ] , 2 , 30 ) , 0 )

   def plotAxes ( self ):
      plotLocation = 30		# Initialize the location of the axes plot
      for axis , value in self.joyAxes.items():		# Loop over all of the joystick axes
         axisValue = self.joystick.get_axis ( axis )	# Get the value of the axis in question
         self.meter ( ( 25 , plotLocation ) , 350 , "Axis " + str ( axis ) , axisValue )	# Call the meter function to plot the value
         plotLocation += 35	# Update the plot location for the next axis
      pygame.display.flip()	# Flip the display

   def plotButtons ( self ):
      # Initialize the button plots
      buttonX = 425
      buttonY = 25
      
      # Clear the quadrant
      pygame.draw.rect ( self.screen , ( 0 , 0 , 0 ) , ( buttonX , buttonY , 400 , 274 ) , 0 )

      # Loop over all of the buttons and plot their current status
      for i in range ( self.buttonCount ):
         if self.joyButtons [ i ] == True:
            pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( buttonX + 25 , buttonY + 25 ) , 25 , 0 )	# Button is pressed -- fill the circle
         else:
            pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( buttonX + 25 , buttonY + 25 ) , 25 , 1 )	# Button is not pressed -- empty circle

         # Label the button
         label = self.labelFont.render ( "Button " + str ( i ) , True , ( 0 , 255 , 0 ) )
         self.screen.blit ( label , ( buttonX , buttonY + 50 ) )

         # Update the button locations
         buttonX += 55
         if buttonX >= 750:
            buttonX = 425
            buttonY += 75

      pygame.display.flip()	# Flip the display

   def plotHat ( self , hat , value ):
      # Initialize the hat display
      hatX = int ( hat / 4 ) * 100 + 405
      hatY = int ( hat % 4 ) * 125 + 305

      # Erase the last drawing
      pygame.draw.rect ( self.screen , ( 0 , 0 , 0 ) , ( hatX , hatY , 100 , 130 ) , 0 )

      # Label the hat
      label = self.labelFont.render ( "Hat " + str ( hat ) , True , ( 0 , 255 , 0 ) )
      self.screen.blit ( label , ( hatX + 30 , hatY + 100 ) )

      # Hat left / right
      if value [ 0 ] == -1:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 25 , hatY + 50 ) , 10 , 0 )	# Hat Left Active -- Draw a filled circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 75 , hatY + 50 ) , 10 , 1 )	# Hat Right Not Active -- Draw an empty circle
      elif value [ 0 ] == 1:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 25 , hatY + 50 ) , 10 , 1 )	# Hat Left Not Active -- Draw an empty circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 75 , hatY + 50 ) , 10 , 0 )	# Hat Right Active -- Draw a filled circle
      else:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 75 , hatY + 50 ) , 10 , 1 )	# Hat Right Not Active -- Draw an empty circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 25 , hatY + 50 ) , 10 , 1 )	# Hat Left Not Active -- Draw an empty circle

      # Hat up / down
      if value [ 1 ] == -1:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 75 ) , 10 , 0 )	# Hat Down Active -- Draw a filled circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 25 ) , 10 , 1 )	# Hat Up Not Active -- Draw an empty circle
      elif value [ 1 ] == 1:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 75 ) , 10 , 1 )	# Hat Down Not Active -- Draw an empty circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 25 ) , 10 , 0 )	# Hat Up Active -- Draw a filled circle
      else:
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 25 ) , 10 , 1 )	# Hat Up Not Active -- Draw an empty circle
         pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( hatX + 50 , hatY + 75 ) , 10 , 1 )	# Hat Down Not Active -- Draw an empty circle

      pygame.display.flip()

   def plotBalls ( self , ball , position ):
      ballX = int ( ball / 4 ) * 100 + 5
      ballY = int ( ball / 4 ) * 125 + 5

      # Clear the old plot
      pygame.draw.rect ( self.screen , ( 0 , 0 , 0 ) , ( ballX , ballY , 100 , 130 ) , 0 )

      # Update the ball location
      self.ballLocations [ ball ] [ 0 ] += position [ 0 ]	# index 0 is the X axis
      self.ballLocations [ ball ] [ 1 ] += position [ 1 ]	# index 1 is the Y axis

      # Keep the ball locations "in bounds"
      if self.ballLocations [ ball ] [ 0 ] < -45: self.ballLocations [ ball ] [ 0 ] = -45
      if self.ballLocations [ ball ] [ 0 ] > 45: self.ballLocations [ ball ] [ 0 ] = 45
      if self.ballLocations [ ball ] [ 1 ] < -45: self.ballLocations [ ball ] [ 1 ] = -45
      if self.ballLocations [ ball ] [ 1 ] > 45: self.ballLocations [ ball ] [ 1 ] = 45

      # Draw a bounding box
      pygame.draw.rect ( self.screen , ( 0 , 255 , 0 ) , ( ballX , ballY , 100 , 100 ) , 1 )

      # Plot the ball location in the box
      pygame.draw.circle ( self.screen , ( 0 , 255 , 0 ) , ( ballX + self.ballLocations [ ball ] [ 0 ] , ballY + self.ballLocations [ ball ] [ 1 ] ) , 2 , 0 )

      # Label the box
      label = self.labelFont.render ( "Ball " + str ( ball ) , True , ( 0 , 255 , 0 ) )
      self.screen.blit ( label , ( ballX + 30 , ballY + 100 ) )

      # Flip the screen
      pygame.display.flip()

   def run ( self ):
      # The PyGame event loop

      running = True	# This is the main "loop running" variable -- set to false to exit the loop
      while running:	# Loop until "running" becomes false
         for event in pygame.event.get():	# Get all of the events from the queue
            if event.type == pygame.JOYAXISMOTION:		# Main axis movement
               self.joyAxes [ event.axis ] = event.value
               self.plotAxes()
            elif event.type == pygame.JOYBUTTONDOWN:		# Buttons pressed
               self.joyButtons [ event.button ] = True
               self.plotButtons()
            elif event.type == pygame.JOYBUTTONUP:		# Buttons released
               self.joyButtons [ event.button ] = False
               self.plotButtons()
            elif event.type == pygame.JOYHATMOTION:		# Change in hat position
               self.plotHat ( event.hat , event.value )
            elif event.type == pygame.JOYBALLMOTION:		# Change in trackball position
               self.plotBalls ( event.ball , event.rel )

# Setup the joysticks
pygame.joystick.init()
stickCount = pygame.joystick.get_count()	# How many joysticks are connected?

for index in range ( stickCount ):		# Print the name of each joystick
   joystick = pygame.joystick.Joystick ( index )
   print ( "{0}) {1}".format ( index , joystick.get_name() ) )

# Get the user's selection, and exit if they just press enter
selected = input ( "Enter a joystick number or just Enter to exit:" )
if selected == "": sys.exit

# Convert the selection into an integer
index = int ( selected )

# Initialize the selected joystick
joystick = pygame.joystick.Joystick ( index )
joystick.init()

# Initialize the pygame display
pygame.display.init()
screen = pygame.display.set_mode ( ( 800 , 600 ) )
pygame.display.set_caption ( "Joystick tester" )

# Initialize the display class
window = mainDisplay ( screen , joystick )

# Start the main loop
window.run()
