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.helper.workbook.wrapper.NomenclatureDescFrWrapper;
import de.avatic.taricdb.model.NomenclatureDesc;
import de.avatic.taricdb.service.ReferenceStorageService;

public class NomenclatureFrConverter implements ExcelTableConverter<NomenclatureDescFrWrapper> {

	private ReferenceStorageService referenceStorageService;


	public NomenclatureFrConverter(ReferenceStorageService referenceStorageService) {
		this.referenceStorageService = referenceStorageService;

	}
	
	@Override
	public Collection<NomenclatureDescFrWrapper> convert(ExcelTable table) {
		
		Collection<NomenclatureDescFrWrapper> nomenclatures = new ArrayList<>();


		table.getRows().forEach((row) -> {
			if (row.index() == 0) {
				return;
			}

			String goodsCode = row.getAs("Goods code", String.class);

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

			String hsCode = goodsCode.substring(0, 10);
			String suffix = goodsCode.substring(11, 13);

			NomenclatureDescFrWrapper nomenclature = nomenclatures.stream().filter(n -> n.getHscode().equals(hsCode) && n.getSuffix().equals(suffix)).findAny().orElse(null);
					
			
			if (nomenclature == null) {
				nomenclature = new NomenclatureDescFrWrapper(new NomenclatureDesc(row.getAs("Language", String.class), row.getAs("Description", String.class), row.getAs("Descr. start date", LocalDate.class)), hsCode, suffix);
				nomenclatures.add(nomenclature);
			}
			else
			{
				throw new IllegalArgumentException("Duplicate hscode found: " + hsCode + " " + suffix);
			}

		});

		return nomenclatures;
	}

}
