# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# This file is part of clive.
#
# clive 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.
#
# clive 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 clive.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################

## Contains the program entry point class

# Do no cache these imports: they are not used in any other files
import traceback

__all__ = ['Clive']

from clive.opts import Options
from clive.nomad import Nomad
from clive.unicode import tostr
from clive.modules import Modules

## The program class
class Clive:

    ## Constructor
    def __init__(self):
        m = Modules() # Init modules cache
        self._sys = m.getinst('sys')
        self._sys.excepthook = self._exc_hook
        self._opts = Options()
        self._opts.parse()

    ## The entry point
    def main(self):
        self._opts.show(self._say)
        Nomad().run(self._say)

    def _say(self, text='\n', show_always=0, is_error=0, newline=1, flush=0):
        opts = self._opts._opts
        if opts.enable_verbose or show_always:
            std = ([self._sys.stdout, self._sys.stderr][is_error])
            if is_error and not text.startswith('error:'):
                text = 'error: ' + text
            text = tostr(text)
            std.write(self._cleanup_text(text, newline))
            if flush: std.flush()

    def _cleanup_text(self, text, newline):
        text = text.rstrip('\r\n')
        if newline: text += '\n'
        return text

    def _exc_hook(self, type, value, tb):
        if type != EOFError and type != KeyboardInterrupt:
            trace = Modules().getinst('StringIO')
            traceback.print_exception(type, value, tb, None, trace)
            self._sys.stderr.write('error: %s\n' % trace.getvalue())
        else:
            print


