package jnpf.ureport.build;

import jnpf.ureport.cell.CellBuilder;
import jnpf.ureport.cell.down.DownExpandBuilder;
import jnpf.ureport.cell.none.NoneExpandBuilder;
import jnpf.ureport.cell.right.RightExpandBuilder;
import jnpf.ureport.definition.Expand;
import jnpf.ureport.definition.ReportDefinition;
import jnpf.ureport.model.Cell;
import jnpf.ureport.model.Report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ReportBuilder {
    private Map<Expand, CellBuilder> cellBuildersMap = new HashMap<>();

    public ReportBuilder() {
        cellBuildersMap.put(Expand.Down, new DownExpandBuilder());
        cellBuildersMap.put(Expand.None, new NoneExpandBuilder());
        cellBuildersMap.put(Expand.Right, new RightExpandBuilder());
    }


    public Report buildReport(ReportDefinition reportDefinition) {
        Report report = reportDefinition.newReport();
        Map<String, Dataset> datasetMap = reportDefinition.getDatasetMap();
        Context context = new Context(this, report, datasetMap);
        List<Cell> cells = new ArrayList<>();
        cells.add(report.getRootCell());
        do {
            buildCell(context, cells);
            cells = context.nextUnprocessedCells();
        } while (cells != null);
        return report;
    }

    public void buildCell(Context context, List<Cell> cells) {
        if (cells == null) {
            cells = context.nextUnprocessedCells();
        }
        if (cells == null) {
            return;
        }
        CellBuilder noneExpandBuilder = new NoneExpandBuilder();
        for (Cell cell : cells) {
            List<BindData> dataList = context.buildCellData(cell);
            cell.setProcessed(true);
            int size = dataList.size();
            Cell lastCell = cell;
            if (size == 1) {
                lastCell = noneExpandBuilder.buildCell(dataList, cell, context);
            } else if (size > 1) {
                CellBuilder cellBuilder = cellBuildersMap.get(cell.getExpand());
                lastCell = cellBuilder.buildCell(dataList, cell, context);
            }
        }
    }


}
