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

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

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

public class LegalBase2Converter implements ExcelTableConverter<LegalBase> {

    private ReferenceStorageService referenceStorage;

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

    @Override
    public Collection<LegalBase> convert(ExcelTable table) {
        Collection<LegalBase> legalBases = new ArrayList<>();

        Collection<LegalBase> existingLegalBases = referenceStorage.getEntites(LegalBase.class);

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

            String legalBaseStr = row.getAs("Legal base", String.class);

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

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

            LegalBase foundLegalBase = existingLegalBases.stream().filter(s -> s.getLegalBase().equals(legalBaseStr)).findAny()
                    .orElse(null);

            if (foundLegalBase == null) {
                LegalBase legalBase = new LegalBase(legalBaseStr, null, null, null);
                legalBases.add(legalBase);
            }
        });

        return legalBases;

    }
}
