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

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.helper.workbook.wrapper.GeoGroupMembershipWrapper;
import de.avatic.taricdb.model.GeoGroup;
import de.avatic.taricdb.model.GeoGroupDesc;
import de.avatic.taricdb.service.ReferenceStorageService;

public class GeoGroupConverter implements ExcelTableConverter<GeoGroup> {

	private ReferenceStorageService referenceStorage;

	public GeoGroupConverter(ReferenceStorageService referenceStorage) {
		this.referenceStorage = referenceStorage;
	}

	@Override
	public Collection<GeoGroup> convert(ExcelTable table) {
		Collection<GeoGroup> groups = new ArrayList<>();
		Collection<GeoGroupMembershipWrapper> memberships = referenceStorage.getEntites(GeoGroupMembershipWrapper.class);

		table.getRows().forEach((row) -> {
			String origin = row.getAs("Or./Dest.", String.class);

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

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

			if (isNumeric(origin)) {
				Integer groupId = Integer.parseInt(origin);

				GeoGroup geoGroup = groups.stream().filter(s -> s.getGeoGroupCode().equals(origin)).findAny()
						.orElse(null);

				if (geoGroup == null) {
					Set<GeoGroupMembershipWrapper> foundMemberships = memberships.stream()
							.filter(s -> s.getGeoGroupId().equals(groupId)).collect(Collectors.toSet());

					geoGroup = new GeoGroup(origin, row.getAs("Abbrev.", String.class),
							row.getAs("Start date", LocalDate.class), row.getAs("End date", LocalDate.class),
							foundMemberships.stream().map(GeoGroupMembershipWrapper::getGeoGroupMembership)
									.collect(Collectors.toSet()));
					
					groups.add(geoGroup);
				}

				geoGroup.addGeoGroupDesc(new GeoGroupDesc(row.getAs("Language", String.class),
						row.getAs("Description", String.class), row.getAs("Descr. start date", LocalDate.class)));

			}

		});

		return groups;
	}

	private boolean isNumeric(String str) {
		return str.matches("-?\\d+(\\.\\d+)?"); // match a number with optional '-' and decimal.
	}

}
