#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007-2008 Zuza Software Foundation
#
# This file is part of Virtaal
#
# translate 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 2 of the License, or
# (at your option) any later version.
#
# translate 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import logging
import optparse
import sys
from optparse import OptionParser, make_option, OptionValueError
from os import path

from translate.storage import factory

from virtaal import __version__
from virtaal.common import pan_app


optparse._ = _
usage = _("%prog [options] [translation_file]")
option_list = [
    make_option("--profile",
                action="store", type="string", dest="profile", metavar=_("PROFILE"),
                # l10n: 'profiling' refers to performance testing
                help=_("perform profiling, storing the result to the supplied filename.")),
    make_option("--log",
                action="store", type="string", dest="log", metavar=_("LOG"),
                help=_("turn on logging, storing the result to the supplied filename.")),
    make_option("--config",
                action="store", type="string", dest="config", metavar=_("CONFIG"),
                help=_("use the configuration file given by the supplied filename.")),
    make_option("--debug",
                action="store_true", dest="debug", default=False,
                help=_("enable debugging features")),
]
parser = OptionParser(option_list=option_list, usage=usage, version=__version__.ver)

def main(argv):
    def set_logging(options):
        if options.log is None and not options.debug:
            return
        
        level = options.debug and logging.DEBUG or logging.INFO
        if options.debug:
            format = '%(levelname)7s %(module)s.%(funcName)s:%(lineno)d: %(message)s'
            if sys.version_info[:2] < (2, 5):
                format = '%(levelname)7s %(module)s [%(filename)s:%(lineno)d]: %(message)s'
        else:
            format = '%(asctime)s %(levelname)s %(message)s'
        if options.log is None:
            logging.basicConfig(level=level, format=format, stream=sys.stderr)
        elif options.log.upper() in ('-', 'STDOUT'):
            logging.basicConfig(level=level, format=format, stream=sys.stdout)
        else:
            try:
                logging.basicConfig(level=level, format=format, filename=path.abspath(options.log), filemode='w')
            except IOError:
                parser.error(_("Could not open log file '%(filename)s'") % {"filename": options.log})
            

    def set_config(options):
        try:
            if options.config != None:
                pan_app.settings = pan_app.Settings(path.abspath(options.config))
        except:
            parser.error(_("Could not read configuration file '%(filename)s'") % {"filename": options.config})

    def get_startup_file(options):
        if len(args) > 1:
            parser.error(_("invalid number of arguments"))
        elif len(args) == 1:
            return args[0]
        else:
            return None

    def get_virtaal_runner(options):
        def run_virtaal(startup_file):
            # The Virtaal class is importer here to allow changes made in this script (eg. pan_app.DEBUG)
            # to be visible to the rest of the program, seeing as Virtaal imports all controllers, which
            # basically imports the the whole core.
            from virtaal.main import Virtaal
            prog = Virtaal(startup_file)
            prog.run()

        def profile_runner(startup_file):
            def profile(profile_file, startup_file):
                import cProfile
                import devsupport.profiling as profiling
                logging.info('Starting profiling run')
                profiler = cProfile.Profile()
                profiler.runcall(run_virtaal, startup_file)
                k_cache_grind = profiling.KCacheGrind(profiler)
                k_cache_grind.output(profile_file)
                profile_file.close()

            try:
                profile(open(options.profile, 'w+'), startup_file)
            except IOError:
                parser.error(_("Could not open profile file '%(filename)s'") % {"filename":options.profile})

        def default_runner(startup_file):
            if not pan_app.DEBUG:
                try:
                    import psyco
                    psyco.full()
                except Exception:
                    pass
            run_virtaal(startup_file)

        if options.profile != None:
            return profile_runner
        else:
            return default_runner

    options, args = parser.parse_args(argv[1:])
    pan_app.DEBUG = options.debug
    set_config(options)
    set_logging(options)
    startup_file = get_startup_file(options)
    runner = get_virtaal_runner(options)
    runner(startup_file)

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