#!/usr/bin/env python

#############################################################################
##
## This file is part of Taurus, a Tango User Interface Library
## 
## http://www.tango-controls.org/static/taurus/latest/doc/html/index.html
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
## 
## Taurus 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 3 of the License, or
## (at your option) any later version.
## 
## Taurus 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 Taurus.  If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################

import sys
import os.path
import optparse 
from PyQt4 import Qt as Qt

import taurus

def env_index(env, env_name):
    env_name = str(env_name)
    for i, e in enumerate(env):
        e = str(e)
        if e.startswith(env_name):
            return i
    return -1

def has_env(env, env_name):
    return env_index(env, env_name) != -1

def get_env(env, env_name):
    env_name = str(env_name)
    for i, e in enumerate(env):
        e = str(e)
        if e.startswith(env_name):
            return e.split("=")[1]
    return None

def append_or_replace_env(env, env_name, env_value, is_path_like=True):
    i = env_index(env, env_name)
    if i == -1:
        env.append(env_name + "=" + env_value)
    else:
        if is_path_like:
            e_n, e_v = env[i].split("=")
            paths = e_v.split(":")
            if not env_value in paths:
                env_value += ":" + e_v
        env[i] = env_name + "=" + env_value

version = "taurusdesigner %s" % (taurus.Release.version)
usage = "Usage: %prog [options] <ui file(s)>"
description = "The Qt designer application customized for taurus"
parser = optparse.OptionParser(version=version, usage=usage, description=description)
parser.add_option("--taurus-path", dest="tauruspath", default="",
                  help="additional directories to look for taurus widgets")
parser.add_option("--qt-designer-path", dest="pyqtdesignerpath", default="",
                  help="additional directories to look for python qt widgets")

options, args = parser.parse_args()

# Tell Qt Designer where it can find the directory containing the plugins
env = Qt.QProcess.systemEnvironment()

# Set PYQTDESIGNERPATH to look inside taurus for designer plugins
taurus_path = os.path.dirname(os.path.abspath(taurus.__file__))
taurus_qt_designer_path = os.path.join(taurus_path, 'qt', 'qtdesigner')

append_or_replace_env(env, "PYQTDESIGNERPATH", taurus_qt_designer_path)

# Set TAURUSQTDESIGNERPATH
if len(options.tauruspath) > 0:
    append_or_replace_env(env, "TAURUSQTDESIGNERPATH", options.tauruspath)
    append_or_replace_env(env, "PYTHONPATH", options.tauruspath)

#print "PYTHONPATH=%s" % get_env(env, "PYTHONPATH")
#print "PYQTDESIGNERPATH=%s" % get_env(env, "PYQTDESIGNERPATH")

# Start Designer.
designer_bin = Qt.QLibraryInfo.location(Qt.QLibraryInfo.BinariesPath)

if sys.platform == "darwin":
    designer_bin.append("/Designer.app/Contents/MacOS/Designer")
else:
    designer_bin.append("/designer")

designer = Qt.QProcess()
designer.setProcessChannelMode(Qt.QProcess.ForwardedChannels)
designer.setEnvironment(env)
designer.start(designer_bin, args)
designer.waitForFinished(-1)

sys.exit(designer.exitCode())