import sys
import logging
import optparse

import informspace.wampserver as wampserver
import informspace.pluginmanager as pluginmanager


def buildOptionParser():
  parser = optparse.OptionParser()
  parser.add_option("-v", "--verbose",
                    action="store_true",
                    dest="verbose", default=False,
                    help="Set Log Level to DEBUG instead of WARNING")
  parser.add_option("-d", "--debug",
                    action="store_true",
                    dest="debug", default=False,
                    help="Activate debug mode")
  parser.add_option("--wsport",
                    action="store", type="int",
                    dest="wsport", default=9000,
                    help="Websocket Port")
  parser.add_option("--httpport",
                    action="store", type="int",
                    dest="httpport", default=None,
                    help="HTTP Port - activates HTTP server when set")
  parser.add_option("--httpdir",
                    action="store", type="string",
                    dest="httpdir", default="../../../webclient/",
                    help="HTTP server serve directory")
  parser.add_option("--xauthmngr",
                    action="store", type="string",
                    dest="xauthmngr", default="",
                    help="Authentification Manager Plugins to exclude (comma separated list)")
  parser.add_option("--xdocstore",
                    action="store", type="string",
                    dest="xdocstore", default="",
                    help="Document Store Plugins to exclude (comma separated list)")
  parser.add_option("--xnotifmngr",
                    action="store", type="string",
                    dest="xnotifmngr", default="",
                    help="Notification Manager Plugins to exclude (comma separated list)")
  return parser

def setupLogging(verbose):
  loglevel = verbose or logging.DEBUG and logging.INFO
  logging.basicConfig(format="%(asctime)s %(levelname)-7s %(name)-8s :: %(message)s",
                      datefmt='%Y-%m-%d %H:%M:%S',
                      level=loglevel)
  logging.getLogger("yapsy").setLevel(logging.INFO)

def main(argv=None):
  argv = argv or sys.argv
  (options, args) = buildOptionParser().parse_args(argv)

  setupLogging(options.verbose)

  logger = logging.getLogger("main")
  logger.info(".")
  logger.info("..")
  logger.info("...")
  logger.info("Starting up ...")

  plugins = pluginmanager.load(excludePlugins={
    'authmngr': options.xauthmngr.split(','),
    'docstore': options.xdocstore.split(','),
    'notifmngr': options.xnotifmngr.split(',')
  })

  wampserver.startServer(plugins,
                         wsport   = options.wsport,
                         httpport = options.httpport,
                         httpdir  = options.httpdir,
                         debug    = options.debug)

if __name__ == "__main__":
  sys.exit(main())

