#!/usr/bin/env python3
import sys
import signal
import logging
from gi.repository import GLib
import dbus.mainloop.glib
from carquinyol.datastore import DataStore
from sugar3 import logger

# setup logger
logger.start('datastore')

# build the datastore
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
connected = True

ds = DataStore()

# and run it
mainloop = GLib.MainLoop()


def handle_disconnect():
    mainloop.quit()
    logging.debug("Datastore disconnected from the bus.")


def handle_shutdown(signum, frame):
    mainloop.quit()
    raise SystemExit("Shutting down on signal %s" % signum)


bus.set_exit_on_disconnect(False)
bus.add_signal_receiver(handle_disconnect,
                        signal_name='Disconnected',
                        dbus_interface='org.freedesktop.DBus.Local')

signal.signal(signal.SIGHUP, handle_shutdown)
signal.signal(signal.SIGTERM, handle_shutdown)


def main():
    try:
        mainloop.run()
    except KeyboardInterrupt:
        logging.info("DataStore shutdown by user")
    except BaseException:
        logging.error("Datastore shutdown with error", exc_info=sys.exc_info())


main()

ds.stop()
