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

import java.util.ArrayList;
import java.util.Collection;

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.model.Unit;
import de.avatic.taricdb.model.UnitDesc;
import de.avatic.taricdb.service.ReferenceStorageService;

public class UnitConverter implements ExcelTableConverter<Unit> {

	public UnitConverter(ReferenceStorageService referenceStorage) {

	}

	@Override
	public Collection<Unit> convert(ExcelTable table) {
		Collection<Unit> units = new ArrayList<>();

		table.getRows().forEach((row) -> {
			String code = row.getAs("Measuremt Unit", String.class);
			String qualifier = row.getAs("Measuremt. unit qualifier", String.class);

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

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

			Unit unit = units.stream().filter(
					s -> s.getUnitCode().equals(code) && (((qualifier == null) && (s.getUnitQualifier() == null))
							|| ((s.getUnitQualifier() != null && qualifier != null)
									&& (s.getUnitQualifier().equals(qualifier)))))
					.findAny().orElse(null);

			if (unit  == null) {


				unit = new Unit(code, qualifier, row.getAs("Label", String.class));
				units.add(unit);
			}

			unit.addUnitDesc(
					new UnitDesc(row.getAs("Lg", String.class), row.getAs("Concatenated descriptions", String.class), null));
		});

		return units;
	}

}
