# This file is part of Pantry, command-line nutrient analysis.
# 
# Version 22, released Saturday, October 13, 2007.
# 
# Copyright 2007 Omari Norman.
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# 
# The above copyright notice and this permission notice shall
# be included in all copies or substantial portions of the
# Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
# Pantry's "built-in" XML validator is a modified version of
# xmlproc.  xmlproc is Copyright 1998-2000 by Lars Marius
# Garshol, Oslo, Norway.
# 
# All Rights Reserved
# 
# Permission to use, copy, modify, and distribute this
# software and its documentation for any purpose and without
# fee is hereby granted, provided that the above copyright
# notice appear in all copies and that modified copies are
# clearly marked as such.
# 
# LARS MARIUS GARSHOL DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LARS MARIUS
# GARSHOL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

""" Help with input/output, especially with Unicode. 

Variables:
    ENCODING is the default system encoding. """

from __future__ import division
import locale
import codecs
from encodings import aliases

class puni(object):
    """ Prints unicode string to file using correct encoding.

    Strictly speaking the argument does not *need* to be a Unicode string,
    but if it is anything other than a Unicode string or a string that
    contains only characters in range(128), you're asking for it... 
    
    More specifically, Python will try to decode such a string first, and
    it will use the ascii codec, which will raise exceptions for a string
    that has anything outside of range(128). 
    
    If outfile is None, use sys.stdout. If encoding is None, use 
    default system encoding."""

    def __init__(self, fh = None, encoding = None):
        import sys
        if fh == None:
            self.outfile = sys.stdout
        else:
            self.outfile = fh
        if encoding is None:
            self.encoding = ENCODING
        else:
            self.encoding = encoding

    def __call__(self, uniStr):
        toWrite = uniStr.encode(self.encoding)
        self.outfile.write(toWrite)
        return toWrite

class ErrorPrinter:
    """ Prints error messages."""
    def __init__(self, outputPuni, prog, default):
        """ Set up ErrorPrinter. Arguments:

        outputPuni - instance of puni to use for printing strings.
        Typically will be a puni instance hooked to stderr.

        prog - program name to use when printing error messages. 
        
        default - default WARNING or ERROR """
        self.output = outputPuni
        self.prog = prog
        self.default = WARNING
        if default:
            self.default = default
    
    def __call__(self, message, eInst = None, type = None):
        """ Prints an error message.

        message is what to print. This will be the first line
        of the error message.

        eInst is an exception instance. It must have an attribute,
        msg, which contains a list of strings to print. The strings
        will be printed, with each preceded by an indent character
        and each followed by a newline.

        type is the global constant WARNING or ERROR. Each is
        printed with an appropriate string. Warnings are non-fatal.
        Errors are fatal; sys.exit(2) is called. If None, default
        to what was set by the constructor."""

        import sys
        if type is None:
            type = self.default
        
        self.output('==========\n')
        if type == WARNING:
            typeStr = u'warning'
        elif type == ERROR:
            typeStr = u'error'
        self.output(u'%s: %s: %s\n' % (self.prog, typeStr, message))

        if eInst:
            for line in eInst.msg:
                self.output(u'%s\n' % line)
        self.output('==========\n')
        
        if type == ERROR:
            sys.exit(2)

### CONSTANTS
# see if encoding is an alias. If it is not, just leave it as is.
_pythonizedEncoding = locale.getdefaultlocale()[1].replace('-', '_').lower()
try:
    ENCODING = aliases.aliases[_pythonizedEncoding].replace('_', '-')
except KeyError:
    ENCODING = locale.getdefaultlocale()[1]

WARNING = 1
ERROR = 2

