#!/usr/bin/env python

import getopt
import imp
import os
import string
import sys

# Server that exposes the links demo program on port 8080
from quixote.publish import Publisher

from compClust.gui import CompClustWeb
from compClust.gui.DatamanagerUI import DatamanagerUI
from compClust.gui.CompClustWebSession import CompClustWebSession, \
                                              CompClustWebSessionManager, \
                                              datamanager, \
                                              load_sources

# generic CompClust imports for shell convienence
from compClust.mlx import datasets
from compClust.mlx import views
from compClust.mlx import labelings
from compClust.mlx import wrapper
from compClust.iplot import IPlotTk as IPlot
from compClust.iplot.views import DatasetRowPlotView
from compClust.mlx import pcaGinzu

def start_shell():
  """Launch an embedded python shell
  """
  msg = ["----------------------------"]
  msg += ["Welcome to CompClust"]
  msg += ["Press Control-D to exit"]
  
  from IPython.Shell import IPythonShellEmbed
  ipshell = IPythonShellEmbed(banner=string.join(msg, os.linesep))
  ipshell()

def start_webserver(run, host, port, read_only, threading=False, browser=False):
  """Launch web server under quixote 2"""
  #script_name = '/publications/pca-bmc-2005/webdemo'
  #root_url= 'http://woldlab.caltech.edu'+script_name
  root_url = 'http://%s:%s' % (host, port)
  def create(root_url=root_url, read_only=read_only, *args, **kwargs):
     return Publisher(DatamanagerUI(root_url, read_only),
                      session_manager = CompClustWebSessionManager(),
                      display_exceptions='html')
    
  print "starting webserver on %s" % (root_url)

  if threading:
    try:
      import thread
      thread.start_new_thread(run, (create, host, port))
      print "."
    except ImportError, e:
      import threading
      class s(threading.Thread):
        def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
          self.handler = args[0]
        def run(self):
          create()
      sThread = s()
      sThread.setDaemon(1)
      sThread.start()
  else:
   run(create, host=host, port=port)
  if browser:
    import webbrowser
    webbrowser.open(root_url)

def getlogin():
  """Get login, since on my system os.getlogin has a bug,
  this is a work around which will also try some unixisms to get the
  default user.
  """
  try:
    return os.getlogin()
  except (OSError, AttributeError), e:
    # try the environment
    if os.environ.has_key('USER'):
      return os.environ['USER']
    elif os.environ.has_key('USERNAME'):
      return os.environ['USERNAME']
    else:
      return 'compclust'
    
def usage():
  print "compclustweb-local driver script"
  print "--browser launch your default web browser"
  print "--configfile|-f <inifile> specify what datasources to load on startup"
  print "--help|-h this usage help."
  print "--host <name> specify the hostname that we should listen to"
  print "--port <port> specify what port to listen to"
  print "--read-only prevent uploading new data into the compclust web session"
  print "--shell-only run without launching webserver"
  print "--user|-u force application to login as a  specific user"
  #print "-s[hared] run in multiuser mode <prevents -user mode>"

def main(argv=None):
  # make a default for launching in interpreters
  if argv is None:
    argv=[None, ]
    
  # default run mode
  CompClustWebSession.force_user = getlogin()
  threading = True
  # use simple server by default
  from quixote.server.simple_server import run
  
  
  host = 'localhost'
  port = 8001
  read_only = False
  browser = False
  shell_only = False
  
  # parse arguments
  opts, args = getopt.getopt(argv[1:], "f:hu:s:", 
                                       ["browser",
                                        "configfile=",
                                        "help", 
                                        "host=",
                                        "port=",
                                        "read-only",
                                        "shell-only",
                                        "server", 
                                        "user=", 
                                        ])
  for opt, optval in opts:
    if opt in ("--browser"):
      # we need to launch with web browser
      browser = True
    elif opt in ('-f', '--configfile'):
      print "loading config", optval
      load_sources(optval)
    elif opt in ('-h', '--help'):
      print usage()
    elif opt in ('--host'):
      host = optval
    elif opt in ('--port'):
      port = int(optval)
    elif opt in ('--read-only'):
      read_only = True
    elif opt in ('--shell-only'):
      shell_only = True
    elif opt in ('-u', '--user'):
      if optval is None:
        optval = os.getlogin()
      print "setting user to", optval
      CompClustWebSession.force_user = optval
    #elif opt in ('-s', '--shared'):
    #  CompClustWebSession.force_user = None
    elif opt in ('-s', '--server'):
      if optval is None:
        raise ValueError("please chose a quixote server")
      elif optval == 'scgi':
        from quixote.server.scgi_server import run
        threading = False
      elif optval == 'simple':
        from quixote.server.simple_server import run
    else:
      raise ("Unrecognized option %s" %(opt))
        
  # launch app
  if threading and not shell_only:
    start_webserver(run, host, port, read_only, threading, browser)

  start_shell()

if __name__ == "__main__":
  args = sys.argv
  sys.argv = args[0:1]
  main(args)
