# -*- coding: utf-8 -*-
'''
wiimote -> mouse interface
$Id$
$URL$
'''

import pygame
from threading import Thread
from Queue import Queue, Empty
import time

# events to use. Is there a way to get ones known to be unused?


wiiuse = None # import within the thread, why do I have to do this?

class wiimote_thread(Thread):
    '''Manage the wiiuse interface'''
    
    def __init__(self, nmotes=1, timeout=5, screenResolution=(660, 370), position='ABOVE'):
        Thread.__init__(self, name='wiimote')
        self.queue = Queue()
        self.startup = Queue()
        self.nmotes = nmotes
        self.timeout = timeout
        self.screenResolution = screenResolution
        self.position = position
        self.selectedWiimoteIndex = 0
        self.setDaemon(1)
        self._paused = False
        self.start()
        self.startup.get(True) # wait for the thread to get started and acquire the motes
        self.eventCallBack = _default_event_cb
    
    def setEventCallBack(self, func) :
        self.eventCallBack = func

    def run(self):
        '''This runs in a separate thread'''
        global wiiuse
        import PyWiiUse as wiiuse # import here to avoid thread problems on windows
        self.wiimotes = wiiuse.init(self.nmotes)
        found = wiiuse.find(self.wiimotes, self.nmotes, self.timeout)
        self.actual_nmotes = wiiuse.connect(self.wiimotes, self.nmotes)
        
        
        if self.nmotes <= 4 :
            for i in range(self.nmotes):
                wiiuse.set_leds(self.wiimotes[i], wiiuse.LED[i])
        else :
            for i in range(4):
                wiiuse.set_leds(self.wiimotes[i], wiiuse.LED[i])

            if self.nmotes == 5 :
                wiiuse.set_leds(self.wiimotes[4], wiiuse.LED_1 | wiiuse.LED_4)
            if self.nmotes == 6 :
                wiiuse.set_leds(self.wiimotes[4], wiiuse.LED_1 | wiiuse.LED_4)
                wiiuse.set_leds(self.wiimotes[5], wiiuse.LED_1 | wiiuse.LED_2 | wiiuse.LED_3 | wiiuse.LED_4)

        self.go = self.actual_nmotes != 0

        self.startup.put(self.go)

        while self.go:
            if self._paused : continue
            try :
                if wiiuse.poll(self.wiimotes, self.nmotes) :
                    for i in range(self.nmotes) :
                        m = self.wiimotes[i]
                        if m[0].event == wiiuse.EVENT:
                            self.eventCallBack(self, i, m)
            except Exception, e:
                print e
                
            while True:
                try:
                    func, args = self.queue.get_nowait()
                except Empty:
                    break
                func(*args)
    
    def pause(self) :
        self._paused  = True
    
    def resume(self) :
        self._paused = False
    
    def selectWiimote(self, wiimoteIndex) :
        self.selectedWiimoteIndex = wiimoteIndex

    def do(self, func, *args):
        '''Run the function in the thread handling the wiimote'''
        self.queue.put((func, args))                    

    def control_cb(self, wmp, attachment, speaker, ir, led, battery):
        '''Could check the battery level and such here'''
        pygame.event.post(pygame.event.Event(WIIMOTE_STATUS,
                                             attachment=attachment,
                                             speaker=speaker,
                                             ir=ir,
                                             led=[led[i] for i in range(4)],
                                             battery=battery,
                                             id=wmp[0].unid))

    def disconnect_cb(self, wmp):
        '''What should we do here?'''
        pygame.event.post(pygame.event.Event(WIIMOTE_DISCONNECT,
                                             id=wmp[0].unid))

    def quit(self):
        '''Go away.'''
        # TODO will crash if self.nmotes > 4
        # for i in range(self.nmotes):
        #     wiiuse.set_leds(self.wiimotes[i], 0)
        #     wiiuse.disconnect(self.wiimotes[i])
        self.go = False

    def get_count(self):
        return self.actual_nmotes


def _default_event_cb(self, id, wmp):
    ''' default callback that emulate a one button mouse '''
    if id != self.selectedWiimoteIndex : return
    wm = wmp[0]
    pos = (wm.ir.x, wm.ir.y)
    pygame.mouse.set_pos(pos)

    eventType = None

    if wm.btns and \
        wiiuse.is_just_pressed(wm, wiiuse.button['B']) :
            event = pygame.event.Event(pygame.MOUSEBUTTONDOWN,
                                       pos = pos,
                                       button = 1)
            pygame.event.post(event)

    if wm.btns_released and \
        wiiuse.is_released(wm, wiiuse.button['B']):
            event = pygame.event.Event(pygame.MOUSEBUTTONUP,
                                       pos = pos,
                                       button = 1)
            pygame.event.post(event)

def _full_mouse_event_cb(self, id, wmp):
    ''' callback that emulate a 2 buttons mouse with wheel '''
    if id != self.selectedWiimoteIndex : return
    wm = wmp[0]
    pos = (wm.ir.x, wm.ir.y)
    pygame.mouse.set_pos(pos)

    eventType = None

    if wm.btns :
        button = 0
        if wiiuse.is_just_pressed(wm, wiiuse.button['B']) :
            button = 1
        elif wiiuse.is_just_pressed(wm, wiiuse.button['A']) :
            button = 2
        elif wiiuse.is_just_pressed(wm, wiiuse.button['Up']) :
            button = 4
        elif wiiuse.is_just_pressed(wm, wiiuse.button['Down']) :
            button = 5

        if button :
            event = pygame.event.Event(pygame.MOUSEBUTTONDOWN,
                                       pos = pos,
                                       button = button)
            pygame.event.post(event)

    if wm.btns_released :
        button = 0
        if wiiuse.is_released(wm, wiiuse.button['B']) :
            button = 1
        elif wiiuse.is_released(wm, wiiuse.button['A']) :
            button = 2
        elif wiiuse.is_released(wm, wiiuse.button['Up']) :
            button = 4
        elif wiiuse.is_released(wm, wiiuse.button['Down']) :
            button = 5
        
        if button :
            event = pygame.event.Event(pygame.MOUSEBUTTONUP,
                                       pos = pos,
                                       button = button)
            pygame.event.post(event)


WT = None

def init(nmotes, timeout, screenResolution=(660, 370), position='ABOVE'):
    '''Initialize the module.'''
    global WT
    if WT:
        return
    
    WT = wiimote_thread(nmotes, timeout, screenResolution, position)
    
    nmotes = get_count()
    for i in range(nmotes) :
        wm = Wiimote(i) # access the wiimote object
        wm.enable_accels(0) # turn off acceleration reporting
        wm.enable_ir(1, vres = screenResolution, position=position)


def get_count():
    '''How many Wiimotes were found?'''
    return WT.get_count()

def quit():
    '''Gracefully shutdown the connection and turn off the wiimote leds'''
    WT.quit()
    WT.join()

class wiimote(object):
    '''Object representing a Wiimote'''
    def __init__(self, n):
        self.wm = WT.wiimotes[n]

    def enable_leds(self, m):
        '''Control leds. The lower 4 bits map to the 4 leds'''
        WT.do(wiiuse.set_leds, self.wm, sum([wiiuse.LED[i] for i in range(4) if m & (1<<i)]))

    def enable_rumble(self, on):
        '''Control rumble'''
        WT.do(wiiuse.rumble, self.wm, on)

    def enable_accels(self, on):
        '''Control reporting of accelerometer data.'''
        WT.do(wiiuse.motion_sensing, self.wm, on)

    def enable_ir(self, on, vres=None, position=None, aspect=None):
        '''Control reporting IR data.'''
        WT.do(wiiuse.set_ir, self.wm, on)
        if vres is not None:
            WT.do(wiiuse.set_ir_vres, self.wm, *vres)
        if position is not None:
            WT.do(wiiuse.set_ir_position, self.wm, position)
        if aspect is not None:
            WT.do(wiiuse.set_aspect_ratio, self.wm, aspect)

    def set_flags(self, smoothing=None, continuous=None, threshold=None):
        '''Set flags SMOOTHING, CONTINUOUS, ORIENT_THRESH'''
        enable = disable = 0
        if smoothing is not None:
            if smoothing:
                enable |= wiiuse.SMOOTHING
            else:
                disable |= wiiuse.SMOOTHING
        if continuous is not None:
            if continuous:
                enable |= wiiuse.CONTINUOUS
            else:
                disable |= wiiuse.CONTINUOUS
        if threshold is not None:
            if threshold:
                enable |= wiiuse.ORIENT_THRESH
            else:
                disable |= wiiuse.ORIENT_THRESH
        WT.do(wiiuse.set_flags, self.wm, enable, disable)

    def set_orient_thresh(self, thresh):
        '''Set orientation threshold'''
        WT.do(wiiuse.set_orient_threshold, self.wm, thresh)

    def status(self):
        '''Trigger a status callback.'''
        WT.do(wiiuse.status, self.wm)

    def disconnect(self):
        '''Disconnect this Wiimote'''
        WT.do(wiiuse.disconnect(self.wm))

def Wiimote(n):
    '''Get the object for the nth Wiimote'''
    return wiimote(n)

