/*
 * Purpose:	Export source and translation segments of user selected 
 *		files into TMX-file
 * #Files:	For each source file, writes a file with same name with tmx extension added
 * #Format:	TMX v.1.4
 * #Details:	http://wp.me/p3fHEs-6g
 *
 * @author	Thomas Cordonnier (based on script from Kos Ivantsov)
 * @date	2015-03-02
 * @version	0.3
 */

import javax.swing.JOptionPane 
import javax.swing.JFileChooser
import org.omegat.util.StringUtil
import org.omegat.util.Preferences
import org.omegat.util.TMXReader
import static javax.swing.JOptionPane.*
import static org.omegat.util.Platform.*

def prop = project.projectProperties
if (!prop) {
    final def title = 'Export TMX from selected files'
    final def msg   = 'Please try again after you open a project.'
    showMessageDialog null, msg, title, INFORMATION_MESSAGE
    return
}


srcroot = new File(prop.getSourceRoot())
def sourceroot = prop.getSourceRoot().toString() as String

JFileChooser fc = new JFileChooser(
    currentDirectory: srcroot,
    dialogTitle: "Choose files to export",
    fileSelectionMode: JFileChooser.FILES_ONLY, 
    //the file filter must show also directories, in order to be able to look into them
    multiSelectionEnabled: true)

if(fc.showOpenDialog() != JFileChooser.APPROVE_OPTION) {
    console.println "Canceled"
    return
}

if (!(fc.selectedFiles =~ sourceroot.replaceAll(/\\+/, '\\\\\\\\'))) {
        console.println "Selection outside of ${prop.getSourceRoot()} folder"
        final def title = 'Wrong file(s) selected'
        final def msg   = "Files must be in ${prop.getSourceRoot()} folder."
        showMessageDialog null, msg, title, INFORMATION_MESSAGE
        return
    }

String translator = JOptionPane.showInputDialog("Translator login", Preferences.getPreferenceDefault(Preferences.TEAM_AUTHOR,
                System.getProperty("user.name")))	

    
if (prop.isSentenceSegmentingEnabled())
    segmenting = TMXReader.SEG_SENTENCE
else
    segmenting = TMXReader.SEG_PARAGRAPH

def sourceLocale = prop.getSourceLanguage().toString()
def targetLocale = prop.getTargetLanguage().toString()

def makedirRecursive(File file) { 
    if (! file.exists()) { 
        if (! file.parentFile.exists()) makedirRecursive(file.parentFile);
        file.mkdir();
    }
}

def escape(st) {
    return st.replaceAll("&", "&#x26;").replaceAll("<", "&#x3c;").replaceAll(">","&#x3e;");
}

Thread.start {

    fc.selectedFiles.each {
        def fileloc = it.toString()+'.tmx'
        fileloc = fileloc - "$sourceroot"
        fileloc = prop.projectRoot.toString() + "\\export-omegat\\" + fileloc
        exportfile = new File(fileloc)
        makedirRecursive (exportfile.parentFile)

        exportfile.write("", 'UTF-8')
        exportfile.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", 'UTF-8')
        exportfile.append("<!DOCTYPE tmx SYSTEM \"tmx11.dtd\">\n", 'UTF-8')
        exportfile.append("<tmx version=\"1.4\">\n", 'UTF-8')
        exportfile.append(" <header\n", 'UTF-8')
        exportfile.append("  creationtool=\"OmegaTScripting\"\n", 'UTF-8')
        exportfile.append("  segtype=\"" + segmenting + "\"\n", 'UTF-8')
        exportfile.append("  o-tmf=\"OmegaT TMX\"\n", 'UTF-8')
        exportfile.append("  adminlang=\"EN-US\"\n", 'UTF-8')
        exportfile.append("  srclang=\"" + sourceLocale + "\"\n", 'UTF-8')
        exportfile.append("  datatype=\"plaintext\"\n", 'UTF-8')
        exportfile.append(" >\n", 'UTF-8')
        
        exportfile.append(" </header>\n", 'UTF-8')
        exportfile.append("  <body>\n", 'UTF-8')

        def count = 0

        def fl = "${it.toString()}" - "$sourceroot" 
        console.println ("fl = " + fl)
        def matcher = (fl =~ /([A-Z]+)\-([0-9]{4})\-([0-9]{5})\-([0-9]{2})\-([0-9]{2})\-/) 
        project.projectFiles.each {
            if ( "${it.filePath}" == "$fl" ) {
                it.entries.each {
                    def key = it.key
                    def info = project.getTranslationInfo(it)
                    def changeId = info.changer
                    def changeDate = info.changeDate
                    def creationId = info.creator
                    def creationDate = info.creationDate
                    def alt = 'unknown'
                    if (info.isTranslated()) {
                        source = StringUtil.makeValidXML(it.srcText)
                        target = StringUtil.makeValidXML(info.translation)
                        exportfile.append("    <tu>\n", 'UTF-8')
                        exportfile.append ("      <prop type=\"Txt::Translator\">${changeId ?: alt }</prop>\n", 'UTF-8')
                        if (! info.defaultTranslation) {
                            if (key.file != null) exportfile.append ("      <prop type=\"file\">${key.file}</prop>\n", 'UTF-8')
                            if (key.id != null) exportfile.append ("      <prop type=\"id\">${key.id}</prop>\n", 'UTF-8')
                            if (key.prev != null) exportfile.append ("      <prop type=\"prev\">${key.prev}</prop>\n", 'UTF-8')
                            if (key.next != null) exportfile.append ("      <prop type=\"next\">${key.next}</prop>\n", 'UTF-8')
                            if (key.path != null) exportfile.append ("      <prop type=\"path\">${key.path}</prop>\n", 'UTF-8')
                        }
                        if (info.note != null) exportfile.append ("      <note>${escape(info.note)}</note>\n", 'UTF-8')
                        exportfile.append("      <tuv xml:lang=\"" + sourceLocale + "\">\n", 'UTF-8')
                        exportfile.append("        <seg>$source</seg>\n", 'UTF-8')
                        exportfile.append("      </tuv>\n", 'UTF-8')
                        exportfile.append("      <tuv xml:lang=\"" + targetLocale + "\"", 'UTF-8')
                        exportfile.append(" changeid=\"${translator ?: changeId ?: alt }\"", 'UTF-8')
                        exportfile.append(" changedate=\"${ changeDate > 0 ? new Date(changeDate).format("yyyyMMdd'T'HHmmss'Z'") : alt }\"", 'UTF-8')
                        exportfile.append(" creationid=\"${creationId ?: alt }\"", 'UTF-8')
                        exportfile.append(" creationdate=\"${ creationDate > 0 ? new Date(creationDate).format("yyyyMMdd'T'HHmmss'Z'") : alt }\"", 'UTF-8')
                        exportfile.append(">\n", 'UTF-8')
                        
                        exportfile.append("        <seg>$target</seg>\n", 'UTF-8')
                        exportfile.append("      </tuv>\n", 'UTF-8')
                        exportfile.append("    </tu>\n", 'UTF-8')
                        count++;
                    }
                }		
            }
        }
        
        exportfile.append("  </body>\n", 'UTF-8')
        exportfile.append("</tmx>", 'UTF-8')
        
        console.println "$count TU's written to " + exportfile.toString()
    }

    showMessageDialog null, "Extraction finished", 'TMX file written', INFORMATION_MESSAGE


    return
}