#! /usr/bin/env python
"""
After been configured properly using CMAKE, 
this module allows to:
 - update the environment variable QT_PLUGIN_PATH with Slicer QT Plugin path
 - start the designer
"""

import os
import sys
import subprocess
  
def startDesigner(open_command, argv):
  "Start QT Designer"
  
  addEnvVariable('QT_PLUGIN_PATH', toCygwinPath('@LIBRARY_OUTPUT_DIRECTORY@'))
  openCmd = open_command+'@QT_BINARY_DIR@'+os.sep+argv[0]
  print openCmd
  os.system(openCmd + " " + argv[1])

def toCygwinPath(path):
  "Attempt to convert to a cygwin path"
  if (sys.platform == 'cygwin'):
    os.system('cygpath -u '+path);
    new_path=subprocess.Popen(["cygpath", "-u",path], stdout=subprocess.PIPE).communicate()[0]
  else:
    new_path=path
  return new_path.strip()

def addEnvVariable(name, value):
  "Add variable to environment"

  # If platform is cygwin, force pathseparator to be ':'
  pathsep = os.pathsep
  if (sys.platform == 'cygwin'):
    pathsep = ':'

  # Update OS environment
  if (name in os.environ):
    sep = ''
    if (os.environ[name] != ""):
      sep = pathsep
  
    os.environ[name] += (sep + value)
  
  else:
    os.environ[name] = value


# Entry point
if __name__ == "__main__":
  if (len(sys.argv) > 2):
    print """
designer.py - Start QT Designer with Slicer plugins

Use: python designer.py [UI file]
"""
  else:
    # Default executable name
    executable_name ='designer'
    open_command = ''

  if (len(sys.argv) < 2):
    sys.argv.append("")
    
  # Handle MACOSX case
  if sys.platform == 'darwin':
    executable_name = 'Designer.app'
    open_command = 'open '

  # Update first value to match executable name
  sys.argv[0] = executable_name
  startDesigner(open_command, sys.argv);
