/* 
 * @Purpose:	Export each file in ongoing file system for other users
 * @author:	Thomas CORDONNIER
 * @date:	2016-1-20
 * @version:	1
 * 
 */
 


import static javax.swing.JOptionPane.*
import static org.omegat.util.Platform.*
import org.omegat.util.StaticUtils

def prop = project.projectProperties
if (!prop) {
    final def title = 'Export project to XLIFF files'
    final def msg   = 'Please try again after you open a project.'
    showMessageDialog null, msg, title, INFORMATION_MESSAGE
    return
}
def folder = prop.projectRoot+'script_output/'
projname = new File(prop.getProjectRoot()).getName()
// create folder if it doesn't exist
if (! (new File (folder)).exists())
    (new File(folder)).mkdir()
count = 0
ignorecount = 0
transcount = 0
writecount = 0

def sourceLocale = prop.getSourceLanguage().toString().toLowerCase()
def targetLocale = prop.getTargetLanguage().toString().toLowerCase()
 
project.projectFiles.findall { info -> ! (info.filePath.matches(".(sdl)?xli?ff?\\z")) }.each { fi ->
    xliff_file = new File(folder + fi.filePath +'.xlf')
    xliff_file.write("""<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
""", 'UTF-8')

        xliff_file.append("""  <file original="$fi.filePath" source-language="$sourceLocale" target-language="$targetLocale" datatype="x-application/x-tmx+xml">
    <body>
      <trans-unit id="0" approved="yes">
        <source xml:lang="$sourceLocale"><ph id="filename">==FILENAME: "$fi.filePath"==</ph>
        </source>
        <target xml:lang="$targetLocale" state="final"><ph id="filename">==FILENAME: "$fi.filePath"==</ph>
        </target>
      </trans-unit>
""", 'UTF-8')
    for (j in 0 ..< fi.entries.size()) {
        def state
        def approved = ''
        def unitnote = ''
        def ignore = ''
        ste = fi.entries[j]
        seg_num = ste.entryNum()
        source = ste.getSrcText()
        info = project.getTranslationInfo(ste)
        target = info ? info.translation : null
        if (target == null) {
            state = 'state="needs-translation"'
            target = "$source"
        } else {
            approved = ' approved="yes"'
            state = 'state="final" state-qualifier="exact-match"'
            transcount++
        }
        if (target.size() == 0 )
            target = "<EMPTY>"
        if (info.hasNote())
            unitnote = "\n        <note>${StaticUtils.makeValidXML(info.note)}</note>"
        if (source ==~ /(<\/?[a-z]+[0-9]* ?\/?>){1,5}/ ){
            ignoresource = source
            ignore = 'yes'
        }
        source = source.replaceAll(/(<)(\/?[a-z]+[0-9]* ?\/?)(>)/, /zzz$2zzz/).replaceAll(/</, /zzz#LESSTHEN#zzz/).replaceAll(/>/, /zzz#GREATERTHEN#zzz/).replaceAll(/(zzz)(\/?[a-z]+[0-9]* ?\/?)(zzz)/, /<$2>/)
            
        target = target.replaceAll(/(<)(\/?[a-z]+[0-9]* ?\/?)(>)/, /zzz$2zzz/).replaceAll(/</, /zzz#LESSTHEN#zzz/).replaceAll(/>/, /zzz#GREATERTHEN#zzz/).replaceAll(/(zzz)(\/?[a-z]+[0-9]* ?\/?)(zzz)/, /<$2>/)
            
        source = StaticUtils.makeValidXML(source).replaceAll(/&lt;/, /<ph>&lt;/).replaceAll(/&gt;/, /&gt;<\/ph>/).replaceAll(/zzz#LESSTHEN#zzz/, /&lt;/).replaceAll(/zzz#GREATERTHEN#zzz/, /&gt;/)
            
        target = StaticUtils.makeValidXML(target).replaceAll(/&lt;/, /<ph>&lt;/).replaceAll(/&gt;/, /&gt;<\/ph>/).replaceAll(/zzz#LESSTHEN#zzz/, /&lt;/).replaceAll(/zzz#GREATERTHEN#zzz/, /&gt;/)
            
        tagnumber = source.findAll(/<ph>/).size()
        if (tagnumber > 0) {
            tgnum = 0
            while (tgnum++ <= tagnumber) {
                source = source.replaceFirst(/<ph>/, "<ph id=\"$tgnum\">")
                target = target.replaceFirst(/<ph>/, "<ph id=\"$tgnum\">")
                //console.println "count: "+tagnumber+"\n"+source
            }
        }
        if (source =~ '<ph>')
            source = source.replaceAll('<ph>', '<ph id="orph"')
            
        if (target =~ '<ph>')
            target = target.replaceAll('<ph>', '<ph id="orph">')

        if (ignore != 'yes'){
            xliff_file.append("""\
      <trans-unit id="$seg_num"$approved>
        <source xml:lang="$sourceLocale">$source</source>
        <seg-source><mrk mid="0" mtype="seg">$source</mrk></seg-source>
        <target $state xml:lang="$targetLocale"><mrk mid="0" mtype="seg">$target</mrk></target>$unitnote
      </trans-unit>
""", 'UTF-8')
            writecount++
        }else{
            ignorecount++
        }
        count++
    }
    xliff_file.append("    </body>\n  </file>\n", 'UTF-8')
    xliff_file.append("</xliff>", 'UTF-8')
}
console.println """
${'*'*(xliff_file.toString().size()+12)}
Output file:   $xliff_file
${'*'*(xliff_file.toString().size()+12)}
Segments processed:	$count
Segments written:	$writecount
Segments not written:	$ignorecount
Translated segments written:	$transcount
Untranslated segments written:	${writecount-transcount}
"""

return
