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

import java.time.LocalDate;
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.model.Certificate;
import de.avatic.taricdb.model.CertificateDesc;
import de.avatic.taricdb.model.CertificateType;
import de.avatic.taricdb.service.ReferenceStorageService;

public class CertificateConverter implements ExcelTableConverter<Certificate> {
	
	private ReferenceStorageService referenceStorage;


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

	@Override
	public Collection<Certificate> convert(ExcelTable table) {
		Collection<Certificate> certs = new ArrayList<>();
		Collection<CertificateType> certTypes = referenceStorage.getEntites(CertificateType.class);
		
		table.getRows().forEach((row) -> {
			String code = row.getAs("Certificate code", String.class);
		
            
            if (row.index() == 0) {
                return;
            }

            if (code == null || code.isEmpty()) {
                return;
            }
            
            
            Certificate cert = certs.stream().filter(s -> s.getCertificateCode().equals(code)).findAny().orElse(null);
            
            if (cert == null) {
            	String certTypeCode = String.valueOf(code.charAt(0));
            	CertificateType foundCertType = referenceStorage.getEntites(CertificateType.class).stream().filter(s -> s.getCertificateTypeCode().equals(certTypeCode)).findAny().orElse(null);

            	cert = new Certificate(code, row.getAs("Start date", LocalDate.class), row.getAs("End date", LocalDate.class), foundCertType == null ? null : AggregateReference.to(foundCertType.getId()));
                certs.add(cert);
            }
            
            cert.addCertificateDesc(new CertificateDesc(row.getAs("Language", String.class), row.getAs("Description", String.class), row.getAs("Description start date", LocalDate.class)));

        });
		
		
		return certs;
	}

}
