import static javax.swing.JOptionPane.*

import java.util.zip.*
import java.nio.file.*
import java.io.*

def prop = project.projectProperties
if (!prop) {
    showMessageDialog null, 'Please try again after you open a project.', 'Reformatter', INFORMATION_MESSAGE
    return
}

if (! fileName.toLowerCase().endsWith(".docx"))
	return

String replacement(String contents) {
	return '</w:t></w:r><w:r><w:rPr>' + contents + '</w:rPr><w:t xml:space="preserve">$1$2$3</w:t></w:r><w:r><w:t xml:space="preserve">'
}


def zipFile = new ZipFile(new File(fileName))
ZipOutputStream destFile = new ZipOutputStream(new FileOutputStream(fileName.substring(0,fileName.lastIndexOf(".")) + "-italic.docx")) 
zipFile.entries().each {
    def path = Paths.get(prop.projectRoot+'script_output/tmp-' + fileName.hashCode() + '/' + it.name)
    if(! it.directory) {
        def parentDir = path.getParent()
        if (!Files.exists(parentDir)) 
            Files.createDirectories(parentDir)            
		destFile.putNextEntry(new ZipEntry(it.name))
		if (it.name.endsWith(".xml")) {		// apply the transformation
			def fis = zipFile.getInputStream(it)
			fis.withReader('UTF-8') { reader ->
				reader.eachLine {
					// apply changes to the line
					def res = it
					res = res.replaceAll(/(\s*)\u2460(.+?)\u2776(\s*)/, replacement("<w:i/>"));	
					res = res.replaceAll(/(\s*)\u2461(.+?)\u2777(\s*)/, replacement("<w:b/>"));
					res = res.replaceAll(/(\s*)\u2462(.+?)\u2778(\s*)/, replacement("<w:u/>"));	
					res = res.replaceAll(/(\s*)\u2463(.+?)\u2779(\s*)/, replacement("<w:vertAlign w:val=\"superscript\" />"));	
					res = res.replaceAll(/(\s*)\u2464(.+?)\u277A(\s*)/, replacement("<w:vertAlign w:val=\"subscript\" />"));	
					
					// print the result
					destFile << res.getBytes('UTF-8')
				}
			}
		} else {
			destFile << zipFile.getInputStream(it)
		}
		destFile.closeEntry()			
    }	
}

destFile.close()
zipFile.close()
