# -*- coding: UTF-8 -*-
#    This file is part of arena.
#   
#    arena 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.
#
#    arena is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
#    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 arena.  If not, see <http://www.gnu.org/licenses/>.

## @file
#  This file defines and implements the base exception class from which all
#  exceptions in arena are derived.

from Library.Base.Classwork import AnObject
from Library.String.Utilities import IsPrintable, String

## Determines how an exception will be represented as a string
eStringRepresentation = "{displayName}: {message}\n"

## The default error message
eDefaultErrorMessage = "an error has occurred"

## The base exception class used by nearly all other exceptions generated 
#  by arena.
class AnException(AnObject, Exception, IsPrintable):
    
    ## Construct a new exception instance.  `errorMessage` may be a format
    #  string, in which case the resulting error message generated by the
    #  exception will include the text in `errorMessage` and any parameters
    #  specified by `params`.
    def __init__(Self, errorMessage, *params):      
        AnObject.__init__(Self)
        
        if len(params) > 0:
            Self._message = String.format(errorMessage, *params)
          
        elif len(errorMessage) > 0:
            Self._message = errorMessage
            
    ## Initializer
    def init(Self):
        result = AnObject.init(Self)
        
        if result:
            Self._message = eDefaultErrorMessage
        
        return result
                    
    ## Print a string representation of the exception to standard script output.
    #
    #  The string representation used is that produced by 
    #  AnException.toString().
    def write(Self):        
        print(Self)
        
    # IsPrintable implementation -----------------------------------------------    
    ## Construct a string representation of the exception.
    #
    #  The string is formatted according to the specification provided by 
    #  eStringRepresentation.
    def toString(Self):     
        return eStringRepresentation.format(displayName=Self.displayName(),
          message=Self._message)
          
    # Properties ---------------------------------------------------------------
    ## Return the error message associated with the exception.
    def message(Self):      
        return Self._message

