/* FichothequeLib_Tools - Copyright (c) 2013-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.tools.importation.parsers.thesaurus;

import java.util.HashSet;
import java.util.Set;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.importation.ParentChange;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.thesaurus.metadata.ThesaurusFieldKey;
import net.fichotheque.tools.importation.ParseResultBuilder;
import net.fichotheque.tools.importation.parsers.ImportationParseContext;
import net.fichotheque.tools.importation.parsers.Row;
import net.fichotheque.tools.importation.parsers.handlers.HandlerUtils;
import net.fichotheque.tools.importation.parsers.handlers.IdalphaHandler;
import net.fichotheque.tools.importation.thesaurus.EditMotcleImportBuilder;
import net.fichotheque.tools.importation.thesaurus.EditThesaurusImportBuilder;
import net.fichotheque.utils.ParentChangeUtils;
import net.mapeadores.util.logging.ErrorMessageException;


/**
 *
 * @author Vincent Calame
 */
class CreationRowParser extends ThesaurusRowParser {

    private final EditThesaurusImportBuilder editThesaurusImportBuilder;
    private final ParseResultBuilder parseResultBuilder;
    private final ThesaurusColumns thesaurusColumns;
    private final Set<String> idalphaSet;
    private final Set<Integer> idSet;
    private final ImportationParseContext parseContext;

    private CreationRowParser(EditThesaurusImportBuilder editThesaurusImportBuilder, ParseResultBuilder parseResultBuilder, ThesaurusColumns thesaurusColumns, ImportationParseContext parseContext) {
        this.editThesaurusImportBuilder = editThesaurusImportBuilder;
        this.parseResultBuilder = parseResultBuilder;
        this.thesaurusColumns = thesaurusColumns;
        this.parseContext = parseContext;
        if (thesaurusColumns.getIdIndex() != -1) {
            idSet = new HashSet<Integer>();
        } else {
            idSet = null;
        }
        if (thesaurusColumns.getIdalphaHandler() != null) {
            idalphaSet = new HashSet<String>();
        } else {
            idalphaSet = null;
        }
    }

    @Override
    public EditThesaurusImportBuilder getThesaurusImportBuilder() {
        return editThesaurusImportBuilder;
    }

    @Override
    public void parseRow(int rowNumber, Row row) {
        Thesaurus thesaurus = editThesaurusImportBuilder.getThesaurus();
        int columnCount = row.getColumnCount();
        int idIndex = thesaurusColumns.getIdIndex();
        int newId = -1;
        boolean withFatalError = false;
        if (idIndex != -1) {
            if (idIndex < columnCount) {
                String idString = row.getColumnValue(idIndex).trim();
                try {
                    newId = Integer.parseInt(idString);
                    if (newId < 1) {
                        newId = -1;
                    } else {
                        if (thesaurus.getMotcleById(newId) != null) {
                            parseResultBuilder.existingId(rowNumber, idString);
                            newId = -1;
                        } else {
                            idSet.add(newId);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    parseResultBuilder.notIntegerId(rowNumber, idString);
                }
            }
        }
        IdalphaHandler idalphaHandler = thesaurusColumns.getIdalphaHandler();
        String newIdalpha = null;
        if (idalphaHandler != null) {
            try {
                newIdalpha = idalphaHandler.getIdalpha(row, true);
                if (thesaurus.getMotcleByIdalpha(newIdalpha) != null) {
                    parseResultBuilder.existingIdalpha(rowNumber, newIdalpha);
                    withFatalError = true;
                } else {
                    idalphaSet.add(newIdalpha);
                }
            } catch (ErrorMessageException eme) {
                parseResultBuilder.addParseErrorMessage(rowNumber, eme.getErrorMessage());
                withFatalError = true;
            }

        }
        ParentChange parentChange = null;
        int parentIdIndex = thesaurusColumns.getParentIdIndex();
        IdalphaHandler parentIdalphaHandler = thesaurusColumns.getParentIdalphaHandler();
        if (parentIdIndex != -1) {
            if (parentIdIndex < columnCount) {
                String parentIdString = row.getColumnValue(parentIdIndex).trim();
                if (parentIdString.length() > 0) {
                    try {
                        int parentId = Integer.parseInt(parentIdString);
                        if (parentId < 1) {
                            parentId = -1;
                        } else {
                            if ((thesaurus.getMotcleById(parentId) == null) && (!idSet.contains(parentId))) {
                                parseResultBuilder.unknownId(rowNumber, parentIdString);
                                parentId = -1;
                            } else if (parentId == newId) {
                                parseResultBuilder.selfParent(rowNumber, parentIdString);
                                parentId = -1;
                            }
                        }
                        if (parentId > 0) {
                            parentChange = ParentChangeUtils.toIdParentChange(parentId);
                        }
                    } catch (NumberFormatException nfe) {
                        parseResultBuilder.notIntegerId(rowNumber, parentIdString);
                    }
                }
            }
        } else if (parentIdalphaHandler != null) {
            try {
                String parentIdalpha = parentIdalphaHandler.getIdalpha(row, false);
                if (parentIdalpha != null) {
                    if ((thesaurus.getMotcleByIdalpha(parentIdalpha) == null) && (!idalphaSet.contains(parentIdalpha))) {
                        parseResultBuilder.unknownIdalpha(rowNumber, parentIdalpha);
                        parentIdalpha = null;
                    } else if (parentIdalpha.equals(newIdalpha)) {
                        parseResultBuilder.selfParent(rowNumber, parentIdalpha);
                        parentIdalpha = null;
                    }
                }
                if (parentIdalpha != null) {
                    parentChange = ParentChangeUtils.toIdalphaParentChange(parentIdalpha);
                }
            } catch (ErrorMessageException eme) {
                parseResultBuilder.addParseErrorMessage(rowNumber, eme.getErrorMessage());
            }
        }
        if (withFatalError) {
            return;
        }
        EditMotcleImportBuilder motcleImportBuilder = editThesaurusImportBuilder.getEditMotcleImportBuilder(newId, newIdalpha);
        motcleImportBuilder.setParent(parentChange);
        int statusIndex = thesaurusColumns.getStatusIndex();
        if (statusIndex != -1) {
            String statusString = row.getColumnValue(statusIndex).trim();
            if (!statusString.isEmpty()) {
                try {
                    motcleImportBuilder.setNewStatus(FichothequeConstants.checkMotcleStatus(statusString));
                } catch (IllegalArgumentException iae) {
                    parseResultBuilder.unknownStatus(rowNumber, statusString);
                }
            }
        }
        if (thesaurusColumns.hasLabelHandler()) {
            HandlerUtils.populate(motcleImportBuilder.getLabelChangeBuilder(), thesaurusColumns.getLabelHandlerArray(), row, parseResultBuilder, rowNumber);
        }
        if (thesaurusColumns.hasAttributeHandler()) {
            HandlerUtils.populate(motcleImportBuilder.getAttributeChangeBuilder(), thesaurusColumns.getAttributeHandlerArray(), row);
        }
        if (thesaurusColumns.hasJunctionHandler()) {
            HandlerUtils.populate(motcleImportBuilder.getTiesImportBuilder(), thesaurusColumns.getJunctionHandlers(), row, thesaurus, parseContext);
        }
    }

    static CreationRowParser newInstance(String[] fieldArray, EditThesaurusImportBuilder editThesaurusImportBuilder, ParseResultBuilder parseResultBuilder, ImportationParseContext parseContext) {
        ThesaurusColumns thesaurusColumns = ThesaurusColumns.parse(fieldArray, editThesaurusImportBuilder, parseResultBuilder);
        if ((editThesaurusImportBuilder.getThesaurus().isIdalphaType()) && (thesaurusColumns.getIdalphaHandler() == null)) {
            parseResultBuilder.missingColumn(ThesaurusFieldKey.IDALPHA.toString());
            return null;
        } else {
            return new CreationRowParser(editThesaurusImportBuilder, parseResultBuilder, thesaurusColumns, parseContext);
        }
    }

}
