#!/usr/bin/python3

import sys
from gi.repository import GLib
import dbus
import dbus.service
import dbus.mainloop.glib

whiches = {
    '/okish': [('/okish', {'Serial': '* not an imei *'})],
    '/bad/imei': [('/bad/imei', {'Serial': 'nope'})],
    '/empty': [],
    '/no/imei':  [('/no/imei', {'nothing': 'useful'})],
}

class Mgr(dbus.service.Object):
    which = '/empty'

    def __init__(self, loop, *args):
        super(Mgr, self).__init__(*args)
        self.loop = loop

    @dbus.service.method(dbus_interface="org.ofono.Manager",
                         in_signature="", out_signature="a(oa{sv})")
    def GetModemz(self):
        return whiches[self.which]

    @dbus.service.method(dbus_interface="org.ofono.Manager",
                         in_signature="", out_signature="")
    def Quit(self):
        self.loop.quit()

    @dbus.service.method(dbus_interface="org.ofono.Manager",
                         in_signature="bo", out_signature="")
    def Poke(self, expose, which):
        if expose:
            Mgr.GetModems = Mgr.GetModemz
        elif hasattr(Mgr, "GetModems"):
            del Mgr.GetModems

        if which in whiches:
            Mgr.which = which


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

    bus = dbus.SystemBus()
    try:
        name = dbus.service.BusName("org.brofono", bus)
    except dbus.exceptions.DBusException as e:
        if e.get_dbus_name() == "org.freedesktop.DBus.Error.AccessDenied":
            print("copy data/brofono.conf to /etc/dbus-1/system.d.", file=sys.stderr)
            sys.exit(1)
        raise

    mainloop = GLib.MainLoop()
    mgr = Mgr(mainloop, bus, '/')

    chan = GLib.IOChannel.unix_new(0)
    GLib.io_add_watch(chan, GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP, lambda *_: mainloop.quit())
    GLib.idle_add (lambda: print("started"));

    mainloop.run()
