#!/usr/bin/env python
#
# Copyright (C) 2007 - Mark Dillavou
#
# 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; either version 2, or (at your option)
# any later version.
#
# 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 St, Fifth Floor, Boston, MA 02110-1301  USA.

import os, sys

here = os.path.dirname(sys.argv[0])
installed = False

if here.endswith('bin'):
    datadir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..', 'share', 'emr'))
    installed = True
else:
    datadir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '.'))

from twisted.internet import gtk2reactor
gtk2reactor.install()

from twisted.internet import reactor

import pygtk
pygtk.require('2.0')
import gtk

if installed:
    from emr.Preferences import Preferences
    Preferences().data_dir = datadir

    from emr.Logger import Logger
    from emr.EMRGui import EMRGui
    from emr.DataStore import DataStore

else:
    from src.Preferences import Preferences
    Preferences().data_dir = datadir

    from src.Logger import Logger
    from src.EMRGui import EMRGui
    from src.DataStore import DataStore

if __name__ == '__main__':
    # initialize the logger
    logger = Logger()

    gui = EMRGui()

    # create the data store and check for updates
    DataStore().check_for_updates()

    # start main loop
    reactor.run()
    
    # save out
    DataStore().save()
    Preferences().save_preferences()

    # quit
    reactor.stop()

    # !mwd - I don't know what is going on here.
    #  If i have done a call to deferToThread
    #  then everythings seems to hang after calling
    #  reactor.stop().  Calling exit fixes this ;)
    sys.exit(0)
