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

import com.qmth.boot.tools.excel.handler.RowDataHandler;
import com.qmth.boot.tools.excel.listener.ObjectListener;
import com.qmth.boot.tools.excel.model.RowData;

public class DataArrayHandler implements RowDataHandler {

    private ObjectListener<String[]> listener;

    private int columnNameRow;

    private String[] columnNames;

    public DataArrayHandler(int columnNameRow, ObjectListener<String[]> listener) {
        this.listener = listener;
        this.columnNameRow = columnNameRow;
    }

    @Override
    public void handle(RowData rowData) {
        if (rowData.getRow() == columnNameRow && columnNames == null) {
            buildColumnNames(rowData);
        } else if (rowData.getRow() > columnNameRow && columnNames != null) {
            convertDataArray(rowData);
        }
    }

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

    private void buildColumnNames(RowData rowData) {
        columnNames = rowData.getValues();
    }

    private void convertDataArray(RowData rowData) {
        String[] array = new String[columnNames.length];
        String[] values = rowData.getValues();
        for (int i = 0; i < array.length && i < values.length; i++) {
            array[i] = values[i];
        }
        listener.output(array);
    }

}
