#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Canonical
#
# Authors:
#  Didier Roche <didrocks@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA


import logging
from optparse import OptionParser

import gettext
from gettext import gettext as _

from oneconf.version import *

# add 10 secondes more than CHECK_CONNECT_STATE_DELAY in oneconfeventhandler
# to get it up while USC is running (there is a ping every CHECK_CONNECT_STATE_DELAY)
MIN_TIME_WITHOUT_ACTIVITY = 60*5+10
#MIN_TIME_WITHOUT_ACTIVITY = 30+10
def quit(loop, myservice):
    '''quit if no activity at least in MIN_TIME_WITHOUT_ACTIVITYs'''
    if myservice.activity:
        logging.debug('Some recent activity, still alive for %ss'
                      % MIN_TIME_WITHOUT_ACTIVITY)
        # check if new desktopcouch sync
        myservice.PackageSetHandler.check_if_desktopcouch_refreshed()
        myservice.activity = False
        return True
    logging.debug('No more activity, go to sleep')
    loop.quit()

if __name__ == '__main__':
    usage = _("usage: %prog [options]")
    parser = OptionParser(version= "%prog " + VERSION, usage=usage)
    parser.add_option("--debug", action="store_true", dest="debug",
                      help=_("enable debug mode"))
    (options, args) = parser.parse_args()
    # set verbosity
    if options.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    # do import only now (otherwise, the import of dbus change level of debug)
    import gobject
    from dbus.mainloop.glib import DBusGMainLoop
    from oneconf.dbusconnect import DbusHostsService

    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    myservice = DbusHostsService()
    gobject.timeout_add_seconds(MIN_TIME_WITHOUT_ACTIVITY, quit, loop, myservice)
    loop.run()

