#!/usr/bin/python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2010 Allen Lowe <lallenlowe@gmail.com>
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.
### END LICENSE

# NOTE: although Decimal is not used in this file, we need to import it here to		
# work around bug LP: #688511
from decimal import Decimal

import logging
import glib
import optparse
import os
import dbus
import sys

# Add project root directory (enable symlink, and trunk execution).
PROJECT_ROOT_DIRECTORY = os.path.abspath(
    os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))

if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'dexter'))
    and PROJECT_ROOT_DIRECTORY not in sys.path):
    sys.path.insert(0, PROJECT_ROOT_DIRECTORY)
    os.putenv('PYTHONPATH', PROJECT_ROOT_DIRECTORY)  # for subprocesses

from dexter.app import DexterApp
from dexter.frontend.dialogs.new_contact import NewContactDialog

import gettext
from gettext import gettext as _

if __name__ == "__main__":
    parser = optparse.OptionParser(version="%prog %ver")
    parser.add_option(
        "-v", "--verbose", action="store_true", dest="verbose",
        help=_("Show debug messages"))
    parser.add_option(
        "-n", "--newcontact", action="store_true", dest="newcontact",
        help=_("Only show the New Contact dialog, then exit"))
    parser.add_option(
        "-e", "--editcontact", action="store", type="int", dest="editcontact",
        help=_("Edit Contact from given id, then exit"))
    (options, args) = parser.parse_args()

    # Set the logging level to show debug messages.
    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging enabled')

    if os.path.exists(sys.path[0]+"/data/ui/dexter-main.ui"):
        logging.info("Using data from current dir")
        datadir = sys.path[0]+"/data"
    elif os.path.exists("../data/ui/dexter-main.ui"):
        logging.info("Using data from current dir")
        datadir = "../data"
    elif os.path.exists("./data/ui/dexter-main.ui"):
        logging.info("Running locally")
        datadir = "./data"
    else:
        datadir = "/usr/share/dexter/"

    files_to_import = []
    for arg in sys.argv:
        if os.path.exists(arg):
            if arg.endswith(".vcard") or arg.endswith(".vcf"):
                files_to_import.append(arg)

    session_bus = dbus.SessionBus()
    try:
        dexter_object = session_bus.get_object("org.elementary.dexterapp",
                                    "/org/elementary/dexterapp")
        is_running = True
    except:
        is_running = False

    if is_running:
        dexter_object = session_bus.get_object("org.elementary.dexterserver",
                                        "/org/elementary/dexterserver")
        logging.info("Application already running")
        if options.newcontact:
            method = dexter_object.get_dbus_method("NewContactDialog")
            method()
        else:
            method = dexter_object.get_dbus_method("ShowWindow")
            method()
            if files_to_import:
                method2 = dexter_object.get_dbus_method("ImportVcardPath")
                method2(files_to_import)
    else:
        app = DexterApp(datadir, options)
        app.run()
