#!/usr/bin/env python2.7
__author__="jvale"
__date__ ="$28/Out/2010 10:51:09$"

import logging
import os
import platform
import sys
from utils import agent_logger, url_opener

import constants

# create application support directories
if not os.path.exists(constants.DOWNLOADS_PATH):
    os.makedirs(constants.DOWNLOADS_PATH)
if not os.path.exists(constants.CACHE_PATH):
    os.makedirs(constants.CACHE_PATH)
if not os.path.exists(constants.LOGS_PATH):
    os.makedirs(constants.LOGS_PATH)


# setup logging as early as possible
sys.excepthook = agent_logger.logable_execepthook
agent_logger.create_initial_config(
    constants.LOG_FILENAME,
    [
        'std',
        'root',
        'blackbird',
        'services',
        'agent.controller',
        'agent.ui',
        'agent.workers',
        'chc.reader',
        'ndri.reader',
        'ndri.writer',
        'filesystem',
    ]
)

# redirect stdout and stderr to logging module
class StdOutWrapper:
    def write(self, text):
        logging.getLogger('std').info(text.strip('\n'))
sys.stdout = StdOutWrapper()

class StdErrWrapper:
    def write(self, text):
        logging.getLogger('std').error(text.strip('\n'))
sys.stderr = StdErrWrapper()


# install url openers
url_opener.setup_openers()


import atexit
import locale
from PySide import QtGui


from agent.ui import MainWindow, LoginDialog
from agent.ui import controller
import i18n
from utils import single_instance, user_settings


def cleanup():
    controller.stop_controller()
    single_instance.unregister_instance()

atexit.register(cleanup)

if __name__ == "__main__":
    logging.getLogger('root').info('Starting %s v%s (%s).' % (
            constants.APP_NAME,
            constants.APP_VERSION,
            platform.platform(),
        )
    )

    try:
        single_instance.register_instance()
    except single_instance.InstanceAlreadyRunningError:
        logging.getLogger('root').info('Another instance is already running, quitting.')
        # TODO sys.exit() does not seem to work
        os._exit(-1)

    # set language
    if user_settings.exists(constants.KEY_LANGUAGE):
        code = user_settings.read(constants.KEY_LANGUAGE)
    else:
        try:
            code = locale.getdefaultlocale()[0]
        except:
            code = constants.DEFAULT_LANGUAGE

    i18n.set_language(code)

    # QApplication must be initialized before using any QtGui stuff.
    app = QtGui.QApplication(sys.argv)

    loginDialog = LoginDialog()
    if loginDialog.exec_() == QtGui.QDialog.Rejected:
        controller.stop_controller()
        sys.exit(0)

    window = MainWindow(loginDialog.get_data())
    window.show()

    sys.exit(app.exec_())
