# -*- coding: utf-8 -*-
# Copyright (C) 2006-2008 Søren Roug, European Environment Agency
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# See http://trac.edgewall.org/wiki/WikiFormatting
#
# Contributor(s):
#

import sys, zipfile, xml.dom.minidom
from odf.namespaces import nsdict
from odf.elementtypes import *

IGNORED_TAGS = [
    'draw:a'
    'draw:g',
    'draw:line',
    'draw:object-ole',
    'office:annotation',
    'presentation:notes',
    'svg:desc',
] + [ nsdict[item[0]]+":"+item[1] for item in empty_elements]

INLINE_TAGS = [ nsdict[item[0]]+":"+item[1] for item in inline_elements]


class TextProps:
    """ Holds properties for a text style. """

    def __init__(self):

        self.italic = False
        self.bold = False
        self.fixed = False
        self.underlined = False
        self.strikethrough = False
        self.superscript = False
        self.subscript = False

    def setItalic(self, value):
        if value == "italic":
            self.italic = True
        elif value == "normal":
            self.italic = False

    def setBold(self, value):
        if value == "bold":
            self.bold = True
        elif value == "normal":
            self.bold = False

    def setFixed(self, value):
        self.fixed = value

    def setUnderlined(self, value):
        if value and value != "none":
            self.underlined = True

    def setStrikethrough(self, value):
        if value and value != "none":
            self.strikethrough = True

    def setPosition(self, value):
        if value is None or value == '':
            return
        posisize = value.split(' ')
        textpos = posisize[0]
        if textpos.find('%') == -1:
            if textpos == "sub":
                self.superscript = False
                self.subscript = True
            elif textpos == "super":
                self.superscript = True
                self.subscript = False
        else:
            itextpos = int(textpos[:textpos.find('%')])
            if itextpos > 10:
                self.superscript = False
                self.subscript = True
            elif itextpos < -10:
                self.superscript = True
                self.subscript = False

    def __str__(self):

        return "[italic=%s, bold=i%s, fixed=%s]" % (str(self.italic),
                                          str(self.bold),
                                          str(self.fixed))

class ParagraphProps:
    """ Holds properties of a paragraph style. """

    def __init__(self):

        self.blockquote = False
        self.headingLevel = 0
        self.code = False
        self.title = False
        self.indented = 0

    def setIndented(self, value):
        self.indented = value

    def setHeading(self, level):
        self.headingLevel = level

    def setTitle(self, va
lue):
        self.title = value

    def setCode(self, value):
        self.code = value


    def __str__(self):

        return "[bq=%s, h=%d, code=%s]" % (str(self.blockquote),
                                           self.headingLevel,
                                           str(self.code))


class ListProperties:
    """ Holds properties for a list style. """

    def __init__(self):
        self.ordered = False

    def setOrdered(self,
 value):
        self.ordered = value



class ODF2MoinMoin(object):


    def __init__(self, filepath):
        self.footnotes = []
        self.footnoteCounter = 0
        self.textStyles = {"Standard": TextProps()}
        self.paragraphStyles = {"Standard": ParagraphProps()}
        self.listStyles = {}
        self.fixedFonts = []
        self.hasTitle = 0
        self.lastsegment = None

        # Tags
        self.elements = {
         'draw:page': self.textToString,
         'draw:frame': self.textToString,
         'draw:image': self.draw_image,
         'draw:text-box': self.textToString,
         'text:a': self.text_a,
         'text:note': self.text_note,
        }
        for tag in IGNORED_TAGS:
            self.elements[tag] = self.do_nothing

        for tag in INLINE_TAGS:
            self.elements[tag] = self.inline_markup
        self.elements['text:line-break'] = self.text_line_break
        self.elements['text:s'] = self.text_s
        self.elements['text:tab'] = self.text_tab

        self.load(filepath)

    def processFontDeclarations(self, fontDecl):
        """ Extracts necessary font information from a font-declaration
            element.
            """
        for fontFace in fontDecl.getElementsByTagName("style:font-face"):
            if fontFace.getAttribute("style:font-pitch") == "fixed":
                self.fixedFonts.append(fontFace.getAttribute("style:name"))



    def extractTextProperties(self, style, parent=None):
        """ Extracts text properties from a style element. """

        textProps = TextProps()

        if parent:
            parentProp = self.textStyles.get(parent, None)
            if parentProp:
                textProp = parentProp

        textPropEl = style.getElementsByTagName("style:text-properties")
        if not textPropEl: return textProps

        textPropEl = textPropEl[0]

        textProps.setItalic(textPropEl.getAttribute("fo:font-style"))
        textProps.setBold(textPropEl.getAttribute("fo:font-weight"))
        textProps.setUnderlined(textPropEl.getAttribute("style:text-underline-style"))
        textProps.setStrikethrough(textPropEl.getAttribute("style:text-line-through-style"))
        textProps.setPosition(textPropEl.getAttribute("style:text-position"))

        if textPropEl.getAttribute("style:font-name") in self.fixedFonts:
            textProps.setFixed(True)

        return textProps

    def extractParagraphProperties(self, style, parent=None):
        """ Extracts paragraph properties from a style element. """

        paraProps = ParagraphProps()

        name = style.getAttribute("style:name")

        if name.startswith("Heading_20_"):
            level = name[11:]
            try:
                level = int(level)
                paraProps.setHeading(level)
            except:
                level = 0

        if name == "Title":
            paraProps.setTitle(True)

        paraPropEl = style.getElementsByTagName("style:paragraph-properties")
        if paraPropEl:
            paraPropEl = paraPropEl[0]
            leftMargin = paraPropEl.getAttribute("fo:margin-left")
            if leftMargin:
                try:
                    leftMargin = float(leftMargin[:-2])
                    if leftMargin > 0.01:
                        paraProps.setIndented(True)
                except:
                    pass

        textProps = self.extractTextProperties(style)
        if textProps.fixed:
            paraProps.setCode(True)

        return paraProps


    def processStyles(self, styleElements):
        """ Runs through "style" elements extracting necessary information.
        """

        for style in styleElements:

            name = style.getAttribute("style:name")

            if name == "Standard": continue

            family = style.getAttribute("style:family")
            parent = style.getAttribute("style:parent-style-name")

            if family == "text":
                self.textStyles[name] = self.extractTextProperties(style, parent)

            elif family == "paragraph":
                self.paragraphStyles[name] = \
                                 self.extractParagraphProperties(style, parent)
                self.textStyle