/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.jab.docsearch.converters;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Layout;
import org.apache.poi.POIXMLProperties.CoreProperties;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hwpf.OldWordFileFormatException;
import org.apache.poi.hwpf.extractor.Word6Extractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.jab.docsearch.utils.FileUtils;

/**
 * Class for handling MS Word files.
 *
 * @version $Id$
 */
public class Word
        extends AbstractConverter
        implements ConverterInterface {

    private final String filename;


    /**
     * Constructor
     *
     * @param filename
     */
    public Word(String filename) {
        this.filename = filename;
    }


    /**
     * @see ConverterInterface#parse()
     */
    @Override
	public void parse()
            throws ConverterException {
        if (filename == null) {
            log.error("parse() filename is null");
            throw new ConverterException("Word::parse() filename is null");
        }

        // check file filename
        String fileExt = FileUtils.getFileExtension(filename);

        // Word OOXML
        if ("docx".equals(fileExt)) {
            parseOOXML();
        }
        // Word OLE
        else {
            try {
                // Word 8
                parseWord8();
            }
            catch (OldWordFileFormatException owffe) {
                // Word 6
                parseWord6();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("parse() Word file='" + filename + "'" + Layout.LINE_SEP +
                    "title='" + documentTitle + "'" + Layout.LINE_SEP +
                    "author='" + documentAuthor + "'" + Layout.LINE_SEP +
                    "keywords='" + documentKeywords + "'");
        }
    }


    /**
     * Parse file with Word 6/Word 95 Extractor
     *
     * @throws ConverterException  Converter problem
     */
    private void parseWord6()
            throws ConverterException {

        // get metadata and text
        FileInputStream fin = null;
        Word6Extractor we = null;
        try {
            fin = new FileInputStream(filename);

            we = new Word6Extractor(fin);

            // get meta data
            SummaryInformation si = we.getSummaryInformation();
            documentAuthor = si.getAuthor();
            documentTitle = si.getTitle();
            documentKeywords = si.getKeywords();

            // get text
            documentText = we.getText();
        }
        catch (IOException ioe) {
            log.error("parse() failed at Word file=" + filename, ioe);
            throw new ConverterException("Word::parse() failed at Word file=" + filename, ioe);
        }
        catch (Exception e) {
            log.error("parse() failed at Word file=" + filename, e);
            throw new ConverterException("Word::parse() failed", e);
        }
        finally {
            IOUtils.closeQuietly(fin);
            IOUtils.closeQuietly(we);
        }
    }


    /**
     * Parse file with Word 97/2000/XP/2003 Extractor
     *
     * @throws ConverterException  Converter problem
     * @throws OldWordFileFormatException  Word format is older
     */
    private void parseWord8()
            throws ConverterException {

        // get metadata and text
        FileInputStream fin = null;
        WordExtractor we = null;
        try {
            fin = new FileInputStream(filename);

            we = new WordExtractor(fin);

            // get meta data
            SummaryInformation si = we.getSummaryInformation();
            documentAuthor = si.getAuthor();
            documentTitle = si.getTitle();
            documentKeywords = si.getKeywords();

            // get text
            documentText = we.getText();
        }
        catch (OldWordFileFormatException owffe) {
            log.info("parse() POI called older Word format!");
            throw owffe;
        }
        catch (IOException ioe) {
            log.error("parse() failed at Word file=" + filename, ioe);
            throw new ConverterException("Word::parse() failed at Word file=" + filename, ioe);
        }
        catch (Exception e) {
            log.error("parse() failed at Word file=" + filename, e);
            throw new ConverterException("Word::parse() failed", e);
        }
        finally {
            IOUtils.closeQuietly(fin, we);
        }
    }


    /**
     * Parse file with Word OOXML Extractor
     *
     * @throws ConverterException  Converter problem
     */
    private void parseOOXML()
            throws ConverterException {

        // get metadata and text
        FileInputStream fin = null;
        XWPFWordExtractor xwe = null;
        try {
            fin = new FileInputStream(filename);

            xwe = new XWPFWordExtractor(OPCPackage.open(fin));

            // get meta data
            CoreProperties cp = xwe.getCoreProperties();
            documentAuthor = cp.getCreator();
            documentTitle = cp.getTitle();
            documentKeywords = cp.getKeywords();

            // get text
            documentText = xwe.getText();
        }
        catch (IOException ioe) {
            log.error("parse() failed at Word file=" + filename, ioe);
            throw new ConverterException("Word::parse() failed at Word file=" + filename, ioe);
        }
        catch (Exception e) {
            log.error("parse() failed at Word file=" + filename, e);
            throw new ConverterException("Word::parse() failed", e);
        }
        finally {
            IOUtils.closeQuietly(fin, xwe);
        }
    }
}
