/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atea.nlptools.macroniser.monogram.plugin;

import java.io.File;

import org.atea.nlptools.macroniser.monogram.restorer.XmlRestorer;
import org.atea.nlptools.macroniser.util.FileUtil;
import org.fuin.utils4j.Utils4J;

/**
 *
 * @author OEM
 */
public class XlsxPlugin implements IPlugin
{
    private File tmpdir;

    public XlsxPlugin(File tmpdir) {
        this.tmpdir = tmpdir;
    }

    public File run(PluginConfiguration configuration)
        throws Exception
    {
        File unzipDir = FileUtil.createRandomDirectory(this.tmpdir);
        Utils4J.unzip(configuration.getFile(), unzipDir);
        
        //Restore the sharedStrings.xml file.
        File documentIn = new File(unzipDir, "xl" + File.separator + "sharedStrings.xml");
        File documentOut = new File(unzipDir, "xl" + File.separator + "mi-tmp-sharedStrings.xml");

        XmlRestorer restorer = new XmlRestorer();
        restorer.restore
        (
            documentIn,
            "utf-8",
            documentOut,
            configuration.getPreserveExistingMacrons()
        );

        //Delete the old document.xml and rename the restored document.
        documentIn.delete();
        documentOut.renameTo(new File(unzipDir.getCanonicalPath() + File.separator + "xl" + File.separator + "sharedStrings.xml"));

        //Create a file to store the zipped file.
        File zipFile = File.createTempFile("mi-tmp-", configuration.getFileType(), tmpdir);
        Utils4J.zipDir(unzipDir, null, zipFile);

        //Delete zip directory.
        if (unzipDir.getName().startsWith("mi-tmp-")) {
            FileUtil.deleteFile(unzipDir);
        }

        return zipFile;
    }
}
