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.DataMap;
import com.qmth.boot.tools.excel.model.RowData;

public class DataMapHandler implements RowDataHandler {

    private ObjectListener<DataMap> listener;

    private int columnNameRow;

    private String[] columnNames;

    public DataMapHandler(int columnNameRow, ObjectListener<DataMap> 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) {
            convertDataMap(rowData);
        }
    }

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

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

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

}
