package org.mte.numecoeval.referentiel.domain.ports.input.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO;
import org.mte.numecoeval.referentiel.domain.data.ResultatImport;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.ports.input.ImportCSVReferentielPort;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
public class ImportImpactReseauPortImpl implements ImportCSVReferentielPort<ImpactReseauDTO> {
    private static final String HEADER_REF_RESEAU = "refReseau";
    private static final String HEADER_ETAPE_ACV = "etapeACV";
    private static final String HEADER_CRITERE = "critere";
    private static final String HEADER_VALEUR = "valeur";
    private static final String HEADER_CONSO_ELEC_MOYENNE = "consoElecMoyenne";
    private static final String[] HEADERS = new String[]{
            HEADER_REF_RESEAU, HEADER_ETAPE_ACV, HEADER_CRITERE, HEADER_VALEUR,
            HEADER_CONSO_ELEC_MOYENNE, "source"
    };

    public static String[] getHeaders() {
        return HEADERS;
    }

    public void checkCSVRecord(CSVRecord csvRecord) throws ReferentielException {
        checkAllHeadersAreMapped(csvRecord, HEADERS);
        checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_REF_RESEAU);
        checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_ETAPE_ACV);
        checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_CRITERE);
        checkFieldIsMappedInCSVRecord(csvRecord, HEADER_CONSO_ELEC_MOYENNE);
        checkFieldIsMappedInCSVRecord(csvRecord, HEADER_VALEUR);
    }

    @Override
    public ResultatImport<ImpactReseauDTO> importCSV(InputStream csvInputStream) {
        ResultatImport<ImpactReseauDTO> resultatImport = new ResultatImport<>();
        List<ImpactReseauDTO> dtos = new ArrayList<>();

        try (Reader reader = new InputStreamReader(csvInputStream)) {
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.builder()
                    .setHeader()
                    .setDelimiter(CSV_SEPARATOR)
                    .setTrim(true)
                    .setAllowMissingColumnNames(true)
                    .setSkipHeaderRecord(true)
                    .build().parse(reader);
            records.forEach(csvRecord -> {
                try {
                    checkCSVRecord(csvRecord);
                    dtos.add(ImpactReseauDTO.builder()
                            .critere(csvRecord.get(HEADER_CRITERE).trim())
                            .refReseau(csvRecord.get(HEADER_REF_RESEAU).trim())
                            .consoElecMoyenne(getDoubleValueFromRecord(csvRecord, HEADER_CONSO_ELEC_MOYENNE, null))
                            .valeur(getDoubleValueFromRecord(csvRecord, HEADER_VALEUR, null))
                            .source(csvRecord.get("source").trim())
                            .etapeACV(csvRecord.get(HEADER_ETAPE_ACV).trim())
                            .build());
                } catch (Exception e) {
                    log.error("Erreur prévue lors de la lecture de la ligne {} : {}", csvRecord.getRecordNumber() + 1, e.getMessage());
                    resultatImport.getErreurs().add(e.getMessage());
                }
            });

        } catch (Exception e) {
            log.error("Erreur de traitement du fichier", e);

            resultatImport.setErreurs(Collections.singletonList("Le fichier CSV n'a pas pu être lu."));
            resultatImport.setNbrLignesImportees(0);
            resultatImport.setObjects(null);
            return resultatImport;
        }

        resultatImport.setObjects(dtos);
        resultatImport.setNbrLignesImportees(dtos.size());

        return resultatImport;
    }
}
