#!/usr/bin/python
# PYTHON_ARGCOMPLETE_OK

# import gobject
from gi.repository import GObject as gobject
import dbus.service
import time
import sys
import os
import argparse, argcomplete
from dbus.gi_service import ExportedGObject

from dbus import validate_interface_name
import _dbus_bindings
import inspect

from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties

from oacids.exported import managed
from oacids.exported import service
from oacids.exported.ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE
# http://cyberelk.net/tim/2011/08/16/d-bus-and-python-asynchronous-method-implementation/
# https://coelhorjc.wordpress.com/2014/12/09/howto-write-dbus-service-for-linux-in-python/
# http://stackoverflow.com/questions/34851085/how-to-stop-a-dbus-gobject-loop/34860020#34860020

START_TIME=time.time ()


# TRIGGER_IFACE = IFACE + '.Trigger'


def is_running (bus, NAME):
    request = bus.request_name(NAME, dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
    if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:
      return False
    return True



class Timer (service.NaiveService):
    @dbus.service.method(dbus_interface=IFACE,
                         in_signature='', out_signature='')
    def Exit(self):
      print "Exiting!"
      self.Quit( )
      return
      # self.loop.quit()


    @classmethod
    def App (Klass, args=None):
      from dbus.mainloop.glib import DBusGMainLoop
      DBusGMainLoop (set_as_default=True)
      loop = gobject.MainLoop ()
      dbus.mainloop.glib.threads_init( )

      print "STarting", sys.argv
      bus = dbus.SystemBus( )
      op = make_args_op(args)
      if args.quit or is_running(bus, BUS):
        print "Already running"
        proxy = bus.get_object(BUS, PATH)
        app = dbus.Interface (proxy, IFACE)
        print app
        app.Operate(op)
        # app.Howdy( )
        return app
      else:
        timer = Timer (loop, bus)
        timer.running = True
        timer.operate(op)
        loop.run ()
        timer.running = False
        return timer
        


    @dbus.service.method(dbus_interface=IFACE, in_signature='a{sv}', out_signature='v')
    def Operate(self, kwds):
      return self.operate(kwds)
    def operate(self, kwds):
      print "OPERATE", kwds
      if 'ini_home' in kwds:
        self.ini_home = kwds['ini_home']
      if 'name' in kwds:
        self.name = kwds['name']
      if 'create' in kwds:
        self.Create(kwds['create'])
      return 0

def heartbeat():
    print "Still alive at", time.time () - START_TIME
    return True

def main (args):
  pass

def make_args_op (args):
  op = dict( )
  if args.ini_home:
    op.update(ini_home=args.ini_home)
  if args.name:
    print "setting name", args.name
    op.update(name=args.name)
  if args.create:
    op.update(create=dict(name=args.create))
  return op

def clean_path (p):
  return os.path.realpath(os.path.expanduser(p))

if __name__ == '__main__':
  parser = argparse.ArgumentParser( )
  parser.add_argument('--quit', action='store_true', default=False)
  parser.add_argument('--name')
  parser.add_argument('--ini_home', type=clean_path)
  parser.add_argument('--create')
  argcomplete.autocomplete(parser)
  args = parser.parse_args( )
  main(args)
  app = Timer.App(args)

  if args.quit:
    app.Exit( )
    # app.name = args.name
  # app.dispatch(args)

