#!/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
import warnings
warnings.simplefilter('ignore', RuntimeWarning) # ignore the os.tempnam warning

from twisted.internet import gtk2reactor
gtk2reactor.install()

from twisted.internet import reactor

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

try: # local install
    from src.Preferences import Preferences
    found = False
    for i in ('..', '.', os.path.join('..', 'share', 'emr'), os.path.join('.', 'share', 'emr')):
        try:
            os.stat(os.path.join(os.path.dirname(sys.argv[0]), i, 'images'))
            Preferences().data_dir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), i))
            found = True
            break
        except OSError:
            pass

    from src.Logger import Logger
    from src.EMRGui import EMRGui
    from src.DataStore import DataStore
except ImportError: # global install     
    from emr.Preferences import Preferences
    found = False
    for i in ('..', '.', os.path.join('..', 'share', 'emr'), os.path.join('.', 'share', 'emr')):
        try:
            os.stat(os.path.join(os.path.dirname(sys.argv[0]), i, 'share', 'emr', 'images'))
            Preferences().data_dir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), i))
            found = True
            break
        except OSError:
            pass

    if not found:
        print 'Error location necessary data. Please try reinstalling!'
        sys.exit(1)

    from emr.Logger import Logger
    from emr.EMRGui import EMRGui
    from emr.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)
