/*
 * 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.hssf.extractor.ExcelExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.jab.docsearch.utils.FileUtils;

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

    private final String filename;


    /**
     * Contructor
     *
     * @param filename
     */
    public Excel(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("Excel::parse() filename is null");
        }

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

        // Excel OOXML
        if ("xlsx".equals(fileExt)) {
            parseOOXML();
        }
        // Excel OLE
        else {
            parseExcel8();
        }

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


    /**
     * Parse file with Excel 97/2000/XP/2003 Extractor
     *
     * @throws ConverterException  Converter problem
     */
    private void parseExcel8()
            throws ConverterException {

        // get meta data
        FileInputStream fin = null;
        ExcelExtractor ee = null;
        try {
            fin = new FileInputStream(filename);

            ee = new ExcelExtractor(new POIFSFileSystem(fin));
            ee.setIncludeHeadersFooters(false);
            ee.setIncludeSheetNames(false);

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

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


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

        // get meta data
        FileInputStream fin = null;
        XSSFExcelExtractor xee = null;
        try {
            fin = new FileInputStream(filename);

            xee = new XSSFExcelExtractor(OPCPackage.open(fin));
            xee.setIncludeHeadersFooters(false);
            xee.setIncludeSheetNames(false);

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

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