#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4 
###
#
# Wiican is the legal property of J. Félix Ontañón <felixonta@gmail.com>
# Copyright (c) 2009 J. Félix Ontañón
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation
#
# 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
#
###

import sys
import dbus
import gobject
import pynotify

from dbus.mainloop.glib import DBusGMainLoop

from wiican import wiimotemanager

DBUS_URI = 'org.freedesktop.DBus'
DBUS_PATH = '/org/freedesktop/DBus'

BLUEZ_PATH = '/'
BLUEZ_URI = 'org.bluez'
BLUEZMANAGER_IFACE = 'org.bluez.Manager'

HAL_URI = "org.freedesktop.Hal"
HAL_DEVICE_IFACE = "org.freedesktop.Hal.Device"
HAL_MANAGER_URI = "org.freedesktop.Hal.Manager"
HAL_MANAGER_PATH = "/org/freedesktop/Hal/Manager"

def name_owner_changed_cb(names, old_owner, new_owner):
    if BLUEZ_URI in names:
        connect_bluez_signals()
        
def connect_bluez_signals():
    bus.add_signal_receiver(wiimanager.enable,
            dbus_interface=BLUEZMANAGER_IFACE, signal_name="AdapterAdded")
    bus.add_signal_receiver(wiimanager.disable, 
            dbus_interface=BLUEZMANAGER_IFACE, signal_name="AdapterRemoved")

if __name__ == '__main__':   
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    wiimanager = wiimotemanager.WiimoteManager()

    bus = dbus.SystemBus()

    obj = bus.get_object (DBUS_URI, DBUS_PATH)
    bus_interface = dbus.Interface(obj, DBUS_URI)

    if BLUEZ_URI in bus_interface.ListNames():
        connect_bluez_signals()
    else:
        bus.add_signal_receiver(name_owner_changed_cb, dbus_interface=DBUS_URI,
            signal_name='NameOwnerChanged')

    hal_manager_obj = bus.get_object(HAL_URI, HAL_MANAGER_PATH)
    hal_manager = dbus.Interface(hal_manager_obj, HAL_MANAGER_URI)
    hal_manager.connect_to_signal("DeviceAdded", wiimanager.plug_cb)
    hal_manager.connect_to_signal("DeviceRemoved", wiimanager.unplug_cb)

    gobject.MainLoop().run()
