package com.qmth.boot.tools.excel.parser.impl;

import com.qmth.boot.tools.excel.filter.SheetFilter;
import com.qmth.boot.tools.excel.handler.RowDataHandler;
import com.qmth.boot.tools.excel.parser.ExcelParser;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.InputStream;

public class XlsxParser implements ExcelParser {

    private XlsxSheetContentHandler contentHandler;

    public void parse(InputStream inputStream, SheetFilter sheetFilter, RowDataHandler handler) throws Exception {
        OPCPackage pkg = OPCPackage.open(inputStream);
        XSSFReader reader = new XSSFReader(pkg);

        this.contentHandler = new XlsxSheetContentHandler(handler);
        XMLReader parser = XMLHelper.newXMLReader();
        parser.setContentHandler(
                new XSSFSheetXMLHandler(reader.getStylesTable(), new ReadOnlySharedStringsTable(pkg), contentHandler,
                        new DataFormatter(), false));
        XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) reader.getSheetsData();
        int sheetIndex = -1;
        while (sheets.hasNext()) {
            sheetIndex++;
            InputStream ins = sheets.next();
            if (sheetFilter.match(sheetIndex, sheets.getSheetName())) {
                InputSource sheetSource = new InputSource(ins);
                parser.parse(sheetSource);
                ins.close();
            }
        }
    }

    @Override
    public String[] getColumnNames() {
        return contentHandler.getColumnNames();
    }

}
