#! /usr/bin/python3

from xml.dom import minidom
import sys

def msgIsForFile(msg, f):
    locations=msg.getElementsByTagName("location")
    if locations and locations[0].getAttribute("filename")==f:
        return True
    return False

def isOkMsg(msg):
    translations=msg.getElementsByTagName("translation")
    if not translations or translations[0].getAttribute("type")=="obsolete":
        return False
    return True


def traduit(ref, cible, filename):
    """
    ref est un dictionnaire de référence
    cible est le dictionnaire à modifier.
    On utilise ref pour changer les sources de cible, et enfin on
    exporte ça dans le fichier filename
    """
    refMsg=[ m for m in ref.getElementsByTagName("message") if isOkMsg(m)]
    refDico={}
    for m in refMsg:
        translations=m.getElementsByTagName("translation")
        sources=m.getElementsByTagName("source")
        s=""
        t=""
        if sources and sources[0].firstChild:
            s=sources[0].firstChild.nodeValue
            s.replace("&apos;","'")
            s.replace("&amp;","&")
        if translations and translations[0].firstChild:
            t=translations[0].firstChild.nodeValue
        if s and t:
            refDico[s]=t
    cibleMsg=[ m for m in cible.getElementsByTagName("message") if isOkMsg(m)]
    for m in cibleMsg:
        sources=m.getElementsByTagName("source")
        if sources and sources[0].firstChild:
            s=sources[0].firstChild.nodeValue
            if s in refDico:
                sources[0].firstChild.nodeValue=refDico[s]
                translations=m.getElementsByTagName("translation")
                if translations and not translations[0].firstChild:
                    textnode = cible.createTextNode(s)
                    translations[0].appendChild(textnode)
    open(filename,"w").write(cible.toxml())
    return

if __name__=="__main__":
    tsFileName=sys.argv[1]
    otherName=sys.argv[2]
    doc1=minidom.parse(tsFileName)
    doc2=minidom.parse(otherName)
    traduit(doc1, doc2, otherName+".tmp")
