# -*- coding: iso-8859-15 -*-
# Copyright (c) 2000 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program 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.
#
# This program 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

"""The VCalSax module defines a Sax parser for VCalendar files.
It offers conversions between VCalendar data and a VCalXml DOM
implementation.
"""

__revision__ = "$Id$"

from xml.sax.saxutils import prepare_input_source
from xml.sax import saxlib
from xml.sax.xmlreader import AttributesImpl, AttributesNSImpl
from xml.dom import EMPTY_NAMESPACE
from xml.dom.ext.reader import Sax2
import re

try:
    import codecs
    def to_xml_string(str,encoding):
        try:
            decoder = codecs.lookup(encoding)[1]
            encoder = codecs.lookup('utf-8')[0]
            return encoder(decoder(str)[0])[0]
        except LookupError:
            return str
except ImportError:
    from xml.unicode.iso8859 import wstring
    def to_xml_string(str,encoding):
        if upper(self._encoding) == 'UTF-8':
            return str
        else:
            return wstring.decode(encoding,str).utf8()

# Parser for VCalendar data
class VcfParser(saxlib.XMLReader) :

    def __init__(self):
        saxlib.XMLReader.__init__(self)
        self._handle_namespaces = 0
        
    def parse(self, source):
        try:
            file=source.getByteStream()
        except AttributeError:
            file = source
            
        data = file.readline()
        while data != '' :
            while 1:
                nextLine = file.readline()
                if not nextLine:
                    break
                if nextLine[0] == ' ':
                    data = data.strip() + nextLine[1:]
                    continue
                break
            # VCALENDAR, VEVENT or VTODO
            m = re.search('^[ \t]*BEGIN:[ \t]*(\S*)',data)
            if m :
                vobjname = m.group(1)
                if self._handle_namespaces:
                    self._cont_handler.startElementNS(
                            (EMPTY_NAMESPACE, vobjname),
                            vobjname, AttributesNSImpl({}, {}))
                else:
                    self._cont_handler.startElement(vobjname,AttributesImpl({}))

            else :
                m = re.search('^[ \t]*END:[ \t]*(\S*)',data)
                if m :
                    vobjname = m.group(1)
                    if self._handle_namespaces:
                        self._cont_handler.endElementNS(
                                (EMPTY_NAMESPACE, vobjname), vobjname)
                    else:
                        self._cont_handler.endElement(vobjname)
                else :
                    # VCF property 'propname;paramname=paramvalue:propvalue'
                    m = re.search('^[ \t]*([^\s;:]*);?([^:]*):(.*)',data)
                    if m :
                        propname = m.group(1)
                        propvalue = m.group(3)
                        attrs = {}
                        qnames = {}
                        if m.group(2) != '' :
                            propparams = re.split(';',m.group(2))
                            for i in propparams :
                                try:
                                    (paramname,paramvalue) = re.split('=',i)
                                except:
                                    print "Warning : bad format"
                                    paraname = "Unknown"
                                    paramvalue = "Unkown"
                                qnames[(EMPTY_NAMESPACE,paramname)] = paramname
                                attrs[(EMPTY_NAMESPACE,paramname)] = paramvalue
                            
                                
                        # 'X-' prefixed properties
                        if re.match('X-',propname) :
                            qnames[(EMPTY_NAMESPACE,'x-name')] = 'x-name'
                            attrs[(EMPTY_NAMESPACE,'x-name')] = propname
                            propname = 'extension'
                        
                        propvalue = unicode(propvalue, 'iso-8859-1')

                        self._cont_handler.startElementNS(
                                (EMPTY_NAMESPACE, propname),
                                propname, AttributesNSImpl(attrs, qnames))
                        self._cont_handler.characters(propvalue)
                        self._cont_handler.endElementNS(
                                (EMPTY_NAMESPACE, propname),
                                propname)
            data = nextLine
        file.close()

    def getFeature(self, name):
        if name == saxlib.feature_namespaces:
            return self._handle_namespaces
        elif name == saxlib.feature_namespace_prefixes:
            return 0
        raise saxlib.SAXNotRecognizedException(
                "Feature '%s' not recognized" % name)

    def setFeature(self, name, value):
        if name == saxlib.feature_namespaces:
            self._handle_namespaces = value
        else:
            raise saxlib.SAXNotRecognizedException(
                    "Feature '%s' not recognized" % name)

    def getProperty(self, name):
        if name == saxlib.property_lexical_handler:
            return self._lex_handler
        elif name == saxlib.property_declaration_handler:
            return self._decl_handler
        raise saxlib.SAXNotRecognizedException(
                "Property '%s' not recognized" % name)

    def setProperty(self, name, value):
        if name == saxlib.property_lexical_handler:
            self._lex_handler = value
        elif name == saxlib.property_declaration_handler:
            self._decl_handler = value
        else:
            raise saxlib.SAXNotRecognizedException(
                    "Property '%s' not recognized" % name)

