package de.avatic.taricdb.helper.workbook.converters;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.data.jdbc.core.mapping.AggregateReference;

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.model.Measure;
import de.avatic.taricdb.model.MeasureDesc;
import de.avatic.taricdb.model.MeasureSeries;
import de.avatic.taricdb.service.ReferenceStorageService;

public class MeasureConverter implements ExcelTableConverter<Measure> {
	
	private final ReferenceStorageService referenceStorage;
	
	public MeasureConverter(ReferenceStorageService referenceStorage) {
        this.referenceStorage = referenceStorage;
	}

	@Override
	public Collection<Measure> convert(ExcelTable table) {
		Collection<Measure> measures = new ArrayList<>();		
		Collection<MeasureSeries> series = referenceStorage.getEntites(MeasureSeries.class);


		table.getRows().forEach((row) -> {
			String code = row.getAs("Meas. type", String.class);

			if (row.index() == 0) {
				return;
			}

            if (code == null || code.isEmpty()) {
                return;
            }

			Measure measure = measures.stream().filter(s -> s.getMeasureCode().equals(code)).findAny().orElse(null);
			

			if (measure == null) {
				String seriesCode = row.getAs("Meas. Series", String.class);
				MeasureSeries foundSeries = series.stream().filter(s -> s.getMeasureSeriesCode().equals(seriesCode)).findAny().orElse(null);
				
				measure = new Measure(code, row.getAs("Short descr.", String.class),
						row.getAs("TM code", Integer.class), row.getAs("Start date", LocalDate.class), foundSeries == null ? null : AggregateReference.to(foundSeries.getId()));
				measures.add(measure);
			}

			measure.addMeasureDesc(new MeasureDesc(row.getAs("Language", String.class),
					row.getAs("Description", String.class)));
		
		});

		return measures;
	}

}
