#------------------------------------------------------------
#
#  XML operations
#
#------------------------------------------------------------

import xml.dom.minidom
import re, dircache
import os.path
from   xml.dom.NodeFilter import NodeFilter
from   xml.dom.ext.reader import PyExpat
from   xml.dom import ext

from gallery.picture import Picture

removeDotSlash = re.compile("^\.[\\/]")


def getDOM(xmluri):
    """Return DOM document"""
    reader = PyExpat.Reader()
    return reader.fromUri(xmluri)
    

def elementMod(xmlfile, filename, elementname, newvalue):
    """Modify a given file's element given element name and new value
    Open xml file, iterate through it and print result
    """
    doc = getDOM(xmlfile)
    nit = doc.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, None, 0)

    curr_node =  nit.nextNode()
    while curr_node:
        if curr_node.localName and curr_node.localName == "picture":
            modpicture(curr_node, filename, elementname, newvalue)
        curr_node =  nit.nextNode()

    # show that element text was in fact changed
    print ext.PrettyPrint(doc)


def modpicture(node, filename, elementname, newvalue):
    """Given a node, check if it is the file we want to operate on
    filename element value == file
    if so change value of elementname to newvalue

    The element name 'filename' is hardcoded"""

    fileOK = 0
    element = None
    for curr_node in  node._get_childNodes():
        curr_node.normalize()
        if curr_node.localName and curr_node.localName == "filename":
            if curr_node.firstChild and curr_node.firstChild.data == filename:
                fileOK = 1
            else:
                break
        # store reference to element containing value to change
        if curr_node.localName and curr_node.localName == elementname:
            element = curr_node

    if fileOK:
        element.firstChild.data = newvalue

    return None
        
    
def dir2xml(directory="."):
    """Generate a xml file containing picture elements from
    specified directory"""
    pictures = globFiles(directory)
    xml = []
    for picture in pictures:
        pic = Picture(None, picture)
        pic.getExifDate()
        pic.getXML(xml)
    print "".join(xml)


def globFiles(dir):
    """Find all files of filetype defined pictypes in 'dir'. Return sorted list with filenames or None"""
    
    pictypes = ["jpg", "jpeg", "png", "gif"]
    pictures = []
    
    for pictype in pictypes:
        regex = ".*%s" % pictype
        checkextension = re.compile(regex, re.IGNORECASE)
        for file in dircache.listdir(dir):
            if checkextension.search(file):
                pictures.append(os.path.join(dir, removeDotSlash.sub("", file)))
    return pictures


   
def minidomtest(xmlfile="gallery.xml"):
    """Process xmlfile with minidom"""
    file = open(xmlfile)
    doc = xml.dom.minidom.parse(file)
    changeFilename(doc)
    
    print doc.toprettyxml("  " , "\n")



def changeFilename(node):
    if node is None:
        return
    if node.hasChildNodes():
        for node2 in node.childNodes:
            changeFilename(node2)
    node.normalize()
    if node.nodeType == node.ELEMENT_NODE:
        if node.localName == "filename":
            if node.firstChild.data == "p5190006.jpg":
                print "Found filename", node.firstChild.data
            node.firstChild.data = "KURT WAS HERE"
        print "<%s>"%node.tagName
        if node.attributes is not None and node.attributes.length > 0:
            for attrib in node.attributes:
                print attrib
    if node.nodeType == node.TEXT_NODE:
        print node.data
    else:
        print "NODETYPE", node.nodeType
    return


def expatTest(xmlfile="gallery.xml"):
    reader = PyExpat.Reader()
    doc = reader.fromUri(xmlfile)
    nit = doc.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, None, 0)
    

    curr_node =  nit.nextNode()
    while curr_node:
        #curr_node.normalize()
        print "%s node %s\n"%(curr_node.nodeType, curr_node.nodeName)
        if curr_node.firstChild and curr_node.firstChild.data == "p5190006.jpg":
            print "Found filename", curr_node.firstChild.data
            curr_node.firstChild.data = "KURT WAS HERE"

        curr_node =  nit.nextNode()

    # show that filename text was in fact changed
    print ext.PrettyPrint(doc)
