#!/usr/bin/python -tt
# Schedwi
# Copyright (C) 2012, 2013 Herve Quatremain
#
# This file is part of Schedwi.
#
# Schedwi is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Schedwi 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


"""Web interface"""

from optparse import OptionParser
import os.path
import sys
import gettext
import logging
import logging.handlers
from wsgiref.simple_server import WSGIRequestHandler, make_server

sys.path.insert(0, '/usr/lib/python2.7/site-packages/schedwisrv')

from paste.session import SessionMiddleware
from muntjac.demo.util import InMemorySession
from muntjac.terminal.gwt.server.application_servlet import ApplicationServlet

import parse_config
import config
import system_utils


class MyWSGIRequestHandler(WSGIRequestHandler):

    """Custom WSGIRequestHandler to log to a file rather than stderr."""

    def log_message(self, format, *args):
        logging.info("%s - - [%s] %s" % (self.address_string(),
                                         self.log_date_time_string(),
                                         format % args))


#
# Main
#

gettext.install(config.PACKAGE)

from web.main import Main

parser = OptionParser(version="%prog " + config.PACKAGE_VERSION)
parser.add_option("-c", "--config", dest="conf_file", metavar="FILE",
    help=_("use the configuration file FILE rather than the default one"))
(options, args) = parser.parse_args()

if options.conf_file is not None and not os.path.isfile(options.conf_file):
    sys.stderr.write(_("%s is not a file\n") % options.conf_file)
    sys.exit(1)

parse_config.parse(options.conf_file)
system_utils.change_group(parse_config.GROUP_ID)
system_utils.change_user(parse_config.USER_ID)

lh = logging.handlers.WatchedFileHandler(parse_config.GUI_LOG_FILE)
lh.setFormatter(logging.Formatter(
        '%(asctime)s schedwigui[%(process)d]: %(levelname)s: %(message)s'))
logger = logging.getLogger()
logger.addHandler(lh)
logger.setLevel(logging.INFO)

wsgi_app = ApplicationServlet(Main, debug=False,
                              contextRoot=parse_config.GUI_CONTEXT_ROOT,
                              widgetset='org.muntiacus.MuntjacWidgetSet')
wsgi_app = SessionMiddleware(wsgi_app, session_class=InMemorySession)
httpd = make_server(parse_config.GUI_IFACE_LISTEN,
                    parse_config.GUI_PORT, wsgi_app,
                    handler_class=MyWSGIRequestHandler)
logging.info('Serving...')
httpd.serve_forever()
