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

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

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

import de.avatic.taricdb.helper.workbook.ExcelTable;
import de.avatic.taricdb.helper.workbook.wrapper.NomenclatureFootnoteWrapper;
import de.avatic.taricdb.model.Footnote;
import de.avatic.taricdb.model.NomenclatureFootnote;
import de.avatic.taricdb.service.ReferenceStorageService;

public class NomenclatureFootnoteConverter implements ExcelTableConverter<NomenclatureFootnoteWrapper> {

	private ReferenceStorageService referenceStorage;

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

	@Override
	public Collection<NomenclatureFootnoteWrapper> convert(ExcelTable table) {
		Collection<NomenclatureFootnoteWrapper> nomenclatureFootnoteWrappers = new ArrayList<>();
		Collection<Footnote> footnotes = referenceStorage.getEntites(Footnote.class);


		table.getRows().forEach((row) -> {
			String goodsCode = row.getAs("Goods code", String.class);

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

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

			String hsCode = goodsCode.substring(0, 10);
			String suffix = goodsCode.substring(11, 13);
			
			Footnote footnote = footnotes.stream().filter(f -> f.getFootnote().equals(row.getAs("Footnote code", String.class))).findFirst().orElseThrow( () -> new RuntimeException("Footnote not found: " + row.getAs("Footnote code", String.class)));
						
			NomenclatureFootnoteWrapper foundWrapper = nomenclatureFootnoteWrappers.stream().filter(w -> w.getHsCode().equals(hsCode)).findAny().orElse(null);
			
			if (foundWrapper == null) {
				foundWrapper = new NomenclatureFootnoteWrapper(hsCode, suffix);
				nomenclatureFootnoteWrappers.add(foundWrapper);
			}

			foundWrapper.addNomenclatureFootnote(new NomenclatureFootnote(footnote == null ? null : AggregateReference.to(footnote.getId())));
			
		});
		
		return nomenclatureFootnoteWrappers;
	}

}
