import dbus
import dbus.service
import dbus.glib
from dbus import DBusException
import subscribe
import error
import Config


# Based on the values from NetworkManager/include/NetworkManager.h
# We only care about CONNECTED and DISCONNECTED at the moment.
NM_STATE_CONNECTED = 3
NM_STATE_DISCONNECTED = 4

class FeedReader(dbus.service.Object):
        service_name = "org.gnome.feed.Reader"
        object_path = "/org/gnome/feed/Reader"

        def __init__(self):
		try:
                        self._session_bus = dbus.SessionBus()
                        self._service = dbus.service.BusName(self.service_name, bus=self._session_bus)
                        dbus.service.Object.__init__(self, self._service, self.object_path)
		except Exception, e:
			error.log_exc("Error while initializing dbus connection %s" % e)

        @dbus.service.method("org.gnome.feed.Reader")
	def Subscribe(self, url):
                subscribe.show(url=url)
		return True

class NetworkListener:
        SERVICE_NAME = "org.freedesktop.NetworkManager"
        SERVICE_PATH = "/org/freedesktop/NetworkManager"

        def __init__(self):
                self._config = Config.get_instance()

        def set_state(self, state):
                if state == NM_STATE_CONNECTED:
                        self._config.offline = False
                else:
                        self._config.offline = True

        def active_cb(self, path):
                self._config.offline = False

        def inactive_cb(self, path):
                self._config.offline = True


def start_services():
        fr = FeedReader()

        try:
                systemBus = dbus.SystemBus()
                proxy_obj = systemBus.get_object(NetworkListener.SERVICE_NAME,
                                                 NetworkListener.SERVICE_PATH)

                nl = NetworkListener()
                # don't touch offline if it has been previously set.
                if not Config.get_instance().offline:
                        nl.set_state(proxy_obj.state())

                nm_interface = dbus.Interface(proxy_obj, NetworkListener.SERVICE_NAME)
                nm_interface.connect_to_signal('DeviceNowActive', nl.active_cb)
                nm_interface.connect_to_signal('DeviceNoLongerActive', nl.inactive_cb)
        except DBusException, de:
                error.log("Error while connecting to NetworkManager: %s" % str(de))
