
package de.ivu.elect.jee.presentation.dynamicform;

import java.util.ArrayList;
import java.util.List;

import org.primefaces.extensions.model.dynaform.DynaFormModel;
import org.primefaces.extensions.model.dynaform.DynaFormRow;

public class AdvancedDynaFormModelRowHandler {

  private final List<DynaFormRow> rows = new ArrayList<>();

  private final List<Column> cols = new ArrayList<>();

  private final DynaFormModel model;

  AdvancedDynaFormModelRowHandler(DynaFormModel model) {
    super();

    this.model = model;
  }

  public DynaFormRow getRow(int columnZeroBased) {
    return getColumn(columnZeroBased).getNextRow();
  }

  private Column getColumn(int columnZeroBased) {
    if (cols.size() > columnZeroBased) {
      return cols.get(columnZeroBased);
    } else {
      cols.add(new Column());
      return getColumn(columnZeroBased);
    }
  }

  private void addNewRow() {
    rows.add(model.createRegularRow());
  }

  private class Column {

    private int columnRows = 0;

    public DynaFormRow getNextRow() {
      if (rows.size() > columnRows) {
        DynaFormRow dynaFormRow = rows.get(columnRows);
        columnRows++;
        return dynaFormRow;
      } else {
        addNewRow();
        return getNextRow();
      }
    }
  }
}
