#!/usr/bin/env python2
# Pitivi video editor
#
#       pitivi
#
# Copyright (c) 2005, Edward Hervey <bilboed@bilboed.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser 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
import sys
import string
import locale
import gettext

CONFIGURED_PYTHONPATH = ''
CONFIGURED_GI_TYPELIB_PATH = ''
CONFIGURED_LD_LIBRARY_PATH = ''
CONFIGURED_GST_PLUGIN_PATH = ''
LIBDIR = '/usr/lib/i386-linux-gnu'
localedir = ""


def _prepend_env_path(name, value):
    os.environ[name] = os.pathsep.join(value +
            os.environ.get(name, "").split(os.pathsep))


def jump_through_hoops():
    os.environ["JUMP_THROUGH_HOOPS"] = "1"
    os.execv(sys.argv[0], sys.argv)


# Check if we're in development or installed version and set paths properly
def _in_devel():
    return False


def _add_pitivi_path():
    global localedir
    dir = os.path.dirname(os.path.abspath(__file__))
    root = None
    if _in_devel():
        root = os.path.split(dir)[0]
        sys.path.insert(0, os.path.join(root, "pitivi", "coptimizations",
                    ".libs"))
        localedir = os.path.join(os.path.split(dir)[0], 'locale')
    else:
        root = os.path.join(LIBDIR, 'pitivi', 'python')
        localedir = "/usr/share/locale"

    if not root in sys.path:
        sys.path.insert(0, root)

    # prepend any directories found at configure time if they're not
    # already in the path. (if they are already in the path, the user
    # chose to have it that way, so we leave their order)
    for path in string.split(CONFIGURED_PYTHONPATH, ':'):
        if path not in sys.path:
            sys.path.insert(0, path)

    # Added for i18n
    try:
        locale.setlocale(locale.LC_ALL, '')
        locale.bindtextdomain('pitivi', localedir)
        locale.textdomain('pitivi')
    except:
        print "Couldn't set locale."
    try:
        gettext.bindtextdomain('pitivi', localedir)
        gettext.textdomain('pitivi')
    except:
        print "Couldn't set the gettext domain. Translations will not work."

    if CONFIGURED_LD_LIBRARY_PATH or CONFIGURED_GST_PLUGIN_PATH:
        _prepend_env_path("LD_LIBRARY_PATH", [CONFIGURED_LD_LIBRARY_PATH])
        _prepend_env_path("GST_PLUGIN_PATH", [CONFIGURED_GST_PLUGIN_PATH])

        if "JUMP_THROUGH_HOOPS" not in os.environ:
            # ld caches LD_LIBRARY_PATH at startup so we need to execv() here. LALA.
            jump_through_hoops()

    if CONFIGURED_GI_TYPELIB_PATH:
        _prepend_env_path("GI_TYPELIB_PATH", [CONFIGURED_GI_TYPELIB_PATH])


def _initialize_modules():
    from pitivi.check import initialize_modules
    try:
        initialize_modules()
    except Exception, e:
        print "Failed to initialize modules: ", e


def _check_requirements():
    from pitivi.check import check_requirements

    if not check_requirements():
        sys.exit(2)

def _run_pitivi():
    import pitivi.application as ptv

    # Make it easy for developers to debug the application startup.
    if os.environ.get('PITIVI_DEBUG_NO_UI') == '1':
        print 'Starting Pitivi with no GUI.'
        ptv.GuiPitivi._showGui = lambda *args, **kargs : None

    # Start the real Pitivi, with given arguments.
    sys.exit(ptv.main(sys.argv))


if __name__ == "__main__":
    try:
        _add_pitivi_path()
        _initialize_modules()
        # Dep checks really have to happen here, not in application.py. Otherwise,
        # as soon as application.py starts, it will try importing all the code and
        # the classes in application.py will not even have the opportunity to run.
        # We do these checks on every startup (even outside the dev environment, for
        # soft deps); doing imports and gst registry checks has near-zero cost.
        _check_requirements()
        _run_pitivi()
    except KeyboardInterrupt:
        print "\tPitivi stopped by user with KeyboardInterrupt!"
