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

import com.qmth.boot.tools.excel.handler.RowDataHandler;
import com.qmth.boot.tools.excel.model.RowData;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;

public class XlsxSheetContentHandler implements XSSFSheetXMLHandler.SheetContentsHandler {

    private RowDataHandler handler;

    private RowData rowData;

    public XlsxSheetContentHandler(RowDataHandler handler) {
        this.handler = handler;
    }

    @Override
    public void startRow(int i) {
        rowData = new RowData(i);
    }

    @Override
    public void endRow(int i) {
        if (rowData != null && i == rowData.getRow()) {
            handler.handle(rowData);
        }
    }

    @Override
    public void cell(String cellReference, String formattedValue, XSSFComment comment) {
        try {
            CellReference ref = new CellReference(cellReference);
            //System.out.println("row=" + ref.getRow() + ", column=" + ref.getCol() + ", value=" + formattedValue);
            if (rowData != null && rowData.getRow() == ref.getRow()) {
                rowData.addValue(ref.getCol(), formattedValue);
            }
        } catch (Exception e) {
        }
    }

    public String[] getColumnNames() {
        return handler.getColumnNames();
    }
}
