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

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

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

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.helper.workbook.wrapper.GeoGroupMembershipWrapper;
import de.avatic.taricdb.model.Geo;
import de.avatic.taricdb.model.GeoGroupMembership;
import de.avatic.taricdb.service.ReferenceStorageService;

public class GeoGroupMembershipConverter implements ExcelTableConverter<GeoGroupMembershipWrapper> {

	
	private ReferenceStorageService referenceStorage;

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

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

		table.getRows().forEach((row) -> {

			if (row.index() == 0) {
				return;
			}
			
			Integer group = row.getAs("Country group", Integer.class);

            if (group == null) {
                return;
            }

			String member = row.getAs("Member country", String.class);
			Geo geo = geos.stream().filter(s -> s.getIso3166Code().equals(member)).findAny().orElseThrow(() -> new RuntimeException("Geo not found: " + member));
			Integer memberId = geo.getId();

			GeoGroupMembershipWrapper membership = memberships.stream().filter(s -> s.getGeoGroupId().equals(group) && Objects.equals(s.getGeoGroupMembership().getGeo().getId(), memberId)).findAny().orElse(null);

			if (membership == null) {
				membership = new GeoGroupMembershipWrapper(group, new GeoGroupMembership(row.getAs("Mbship start date", LocalDate.class), row.getAs("Mbship end date", LocalDate.class), AggregateReference.to(memberId)));
				memberships.add(membership);
			}
		});

		return memberships;
	}
}
