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

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

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.model.Geo;
import de.avatic.taricdb.model.GeoDesc;
import de.avatic.taricdb.service.ReferenceStorageService;

public class GeoConverter implements ExcelTableConverter<Geo> {

	private ReferenceStorageService referenceStorage;

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

	@Override
	public Collection<Geo> convert(ExcelTable table) {
		Collection<Geo> geos = new ArrayList<>();
		
		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)) {
                Geo geo = geos.stream().filter(s -> s.getIso3166Code().equals(origin)).findAny().orElse(null);
                
                if (geo == null) {
                    geo = new Geo(origin);
                    geos.add(geo);
                }
                
                geo.addGeoDescription(new GeoDesc(row.getAs("Language", String.class), row.getAs("Description", String.class), row.getAs("Descr. start date", LocalDate.class)));
                
            }
            
  
        });
		
		
		return geos;
	}

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

}
