# coding: UTF-8

# AOISO Outline Processor
# Copyright (C) 2007 H.WAKIMOTO
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

import re
import pdb
import os

from node import AoisoNode
from aoiso.common.aoisoConsts import AoisoConsts as c

try:
    #Python 2.4
    import elementtree.ElementTree as ET
except:
    #Python 2.5
    import xml.etree.ElementTree as ET

class AoisoLogic:
    
    def __init__(self,model):
        self.model = model
        #self.treeView = model.treeView

    def saveDocument(self, path, filterIndex):
        dir,filename = os.path.split(path)
        filename,ext = os.path.splitext(filename)
        if ext.upper()==".XML":
            self.__saveAoisoDocument(path)
        elif ext.upper()==".TXT":
            self.__saveWZText(path)
        else:
            if filterIndex==c.FILE_TYPE_AOISO:
                filename = filename + ".xml"
                path = os.path.join(dir, filename)
                self.__saveAoisoDocument(path)
            elif filterIndex==c.FILE_TYPE_TEXT:
                filename = filename + ".txt"
                path = os.path.join(dir, filename)
                self.__saveWZText(path)
        print "Save Complete ! :"+path
        return (path, dir, filename)

    def openDocument(self, path):
        filetype = self.__getFileType(path)
        if filetype == c.FILE_TYPE_AOISO:
            self.__openAoisoDocument(path)
        elif filetype == c.FILE_TYPE_TEXT:
            self.__openWZText(path)

    def __getFileType(self, filename):
        ext = os.path.splitext(filename)[1].upper()
        if ext==".XML":
            return c.FILE_TYPE_AOISO
        elif ext==".TXT":
            return c.FILE_TYPE_TEXT
        else:
            return c.FILE_TYPE_UNKNOWN

    def __saveAoisoDocument(self, path):
        print "saveAoisoDocument"
        root = ET.Element("document")
        head = ET.SubElement(root,"head")
        docprop = ET.SubElement(head,"document-property")
        docprop.set("date","yyyymmdd")
        body = ET.SubElement(root,"body")

        iter = self.model.get_iter_root()
        while iter :
            self.add2dom(body,iter)
            iter = self.model.iter_next(iter)

        etree = ET.ElementTree(root)

        encode = 'UTF-8'
        fd = file(path, 'wb')
        etree.write(fd, encode)
        fd.close()
        
    def __openAoisoDocument(self, path):
        print "openAoisoDocument"
        fd = file(path, 'rb')
        dom = ET.ElementTree(file=fd)

        self.clearDocument()
        
        document = dom.getroot()
        head = ET.SubElement(document,"head")
        body = ET.SubElement(document,"body")
        items = dom.findall("//body/item")
        for item in items:
            self.domNode2TreeNode(item,None)

    def addchild2dom(self,p_element,p_iter):
        i=0
        while i <= self.model.iter_n_children(p_iter)-1:
            iter = self.model.iter_nth_child(p_iter,i)
            self.add2dom(p_element,iter)
            i+=1

    def add2dom(self,p_element,iter):
        node = self.model.get_value(iter,c.COL_OBJECT)
        if node==None:
            print "node is None"
        item_element = ET.SubElement(p_element,"item")
        element = ET.SubElement(item_element,"text-h")
        element.text = node.title
        for str in node.text.split():
            element = ET.SubElement(item_element,"text-p")
            element.text = str
        self.addchild2dom(item_element,iter)        
 
    def domNode2TreeNode(self,p_item,p_iter):
        iter = self.model.append(p_iter)
        text_h = p_item.find("text-h").text
        text_p = ""
        for element in p_item.getchildren():
            if element.tag =="text-p":
                text_p += element.text + "\r\n"
        node = AoisoNode(text_h,text_p)
        self.model.set_value(iter,c.COL_TEXT,node.title)
        self.model.set_value(iter,c.COL_OBJECT,node)
        elements = p_item.getchildren()
        for element in elements:
            if element.tag == "item":
                self.domNode2TreeNode(element,iter)

    def __openWZText(self, path):
        print "openWZText"
        #TODO:
        f = open(path,"r")
        self.clearDocument()
        s = f.readline()

        while (re.search('^[.]',s) == None) and s:
            print "--body--:" + s
            s = f.readline()

        last_depth = 0
        iter = None
        while s:

            node = AoisoNode("","")

            #title
            print "--title--:" + s
            title = re.sub('^[.]*','',s)
            depth = len(s) - len(title)
            #print "depth:%d" %  depth
            node.title = re.sub('\n','',title)

            #text
            s = f.readline()
            text = ""
            while (re.search('^[.]',s) == None) and s:
                print "--body--:" + s
                text = text + s
                s = f.readline()
            node.text = re.sub('$\n','',text)

            if depth == 1:
                print "depth=1"
                iter = self.model.append(None)
                self.model.setNode(iter, node)
                parent_iter = iter
                last_depth = 1
            else:
                print "depth=%d" % depth
                print "last_depth=%d" % depth
                if last_depth == depth:
                    pass
                elif last_depth > depth:
                    parent_iter = self.model.iter_parent(iter)
                elif last_depth < depth:
                    parent_iter = iter
                iter = self.model.append(parent_iter)
                self.model.setNode(iter, node)
                last_depth = depth
            
    def __saveWZText(self, path):
        print "saveWZText"
        #pdb.set_trace()
        iter = self.model.get_iter_root()
        depth = 0
        f = open(path,"w")
        while iter :
            self._writeWZText(f,iter,depth)
            iter = self.model.iter_next(iter)
        f.close()
     	
    def _writeWZText(self,f,p_iter,depth):
        node = self.model.get_value(p_iter,c.COL_OBJECT)
        dotstr = ""
        for i in range(depth + 1):
            dotstr += "."
        f.write(dotstr+node.title + "\n")
        f.write(node.text + "\n")
        i = 0
        while i <= self.model.iter_n_children(p_iter) - 1:
            iter = self.model.iter_nth_child(p_iter,i)
            self._writeWZText(f,iter,depth + 1)
            i += 1

    def clearDocument(self):
        self.model.clear()

    def appendNode(self, widget):
        print "appendNode"
        self.model.appendNewNode()

    def appendChildNode(self,widget):
        print "appendChildNode"
        self.model.appendNewChildNode()

    def deleteNode(self):
        print "deleteNode"
        iter = self.model.getCurrentIter()
        if iter!=None:
            self.model.remove(self.model.getCurrentIter())

