/* 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 net.fichotheque.FichothequeConstants;
import net.fichotheque.importation.ParentChange;
import net.fichotheque.thesaurus.Motcle;
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 ChangeRowParser extends ThesaurusRowParser {

    private final EditThesaurusImportBuilder editThesaurusImportBuilder;
    private final ParseResultBuilder parseResultBuilder;
    private final ThesaurusColumns thesaurusColumns;
    private final ImportationParseContext parseContext;

    ChangeRowParser(EditThesaurusImportBuilder editThesaurusImportBuilder, ParseResultBuilder parseResultBuilder, ThesaurusColumns thesaurusColumns, ImportationParseContext parseContext) {
        this.editThesaurusImportBuilder = editThesaurusImportBuilder;
        this.parseResultBuilder = parseResultBuilder;
        this.thesaurusColumns = thesaurusColumns;
        this.parseContext = parseContext;
    }

    @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();
        IdalphaHandler idalphaHandler = thesaurusColumns.getIdalphaHandler();
        Motcle motcle = null;
        if (idIndex != -1) {
            if (columnCount <= idIndex) {
                parseResultBuilder.missingIdColumn(rowNumber);
                return;
            }
            String idString = row.getColumnValue(idIndex).trim();
            try {
                int id = Integer.parseInt(idString);
                motcle = thesaurus.getMotcleById(id);
                if (motcle == null) {
                    parseResultBuilder.unknownId(rowNumber, idString);
                }
            } catch (NumberFormatException nfe) {
                parseResultBuilder.notIntegerId(rowNumber, idString);
            }
        } else {
            try {
                String idalpha = idalphaHandler.getIdalpha(row, true);
                motcle = thesaurus.getMotcleByIdalpha(idalpha);
                if (motcle == null) {
                    parseResultBuilder.unknownIdalpha(rowNumber, idalpha);
                }
            } catch (ErrorMessageException eme) {
                parseResultBuilder.addParseErrorMessage(rowNumber, eme.getErrorMessage());
            }
        }
        if (motcle == null) {
            return;
        }
        EditMotcleImportBuilder motcleImportBuilder = editThesaurusImportBuilder.getEditMotcleImportBuilder(motcle);
        String newIdalpha = null;
        if ((idIndex != -1) && (idalphaHandler != null)) {
            try {
                newIdalpha = idalphaHandler.getIdalpha(row, false);
                if ((newIdalpha != null) && (thesaurus.getMotcleByIdalpha(newIdalpha) != null)) {
                    newIdalpha = null;
                    parseResultBuilder.existingIdalpha(rowNumber, newIdalpha);
                }
            } catch (ErrorMessageException eme) {
                parseResultBuilder.addParseErrorMessage(rowNumber, eme.getErrorMessage());
            }
        }
        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) {
                    parentChange = ParentChangeUtils.THESAURUS;
                } else {
                    try {
                        int parentId = Integer.parseInt(parentIdString);
                        if (parentId < 1) {
                            parentChange = ParentChangeUtils.THESAURUS;
                        } else {
                            Motcle parentMotcle = thesaurus.getMotcleById(parentId);
                            if (parentMotcle == null) {
                                parseResultBuilder.unknownId(rowNumber, parentIdString);
                            } else {
                                parentChange = ParentChangeUtils.toIdParentChange(parentMotcle.getId());
                            }
                        }
                    } catch (NumberFormatException nfe) {
                        parseResultBuilder.notIntegerId(rowNumber, parentIdString);
                    }
                }
            } else {
                parentChange = ParentChangeUtils.THESAURUS;
            }
        } else if (parentIdalphaHandler != null) {
            try {
                String parentIdalpha = parentIdalphaHandler.getIdalpha(row, false);
                if (parentIdalpha == null) {
                    parentChange = ParentChangeUtils.THESAURUS;
                } else {
                    Motcle parentMotcle = thesaurus.getMotcleByIdalpha(parentIdalpha);
                    if (parentMotcle == null) {
                        parseResultBuilder.existingIdalpha(rowNumber, newIdalpha);
                    } else {
                        parentChange = ParentChangeUtils.toIdParentChange(parentMotcle.getId());
                    }
                }
            } catch (ErrorMessageException eme) {
                String key = eme.getErrorMessage().getMessageKey();
                if (key.equals("_ error.wrong.idalpha")) {
                    parseResultBuilder.addParseErrorMessage(rowNumber, eme.getErrorMessage());
                } else {
                    parentChange = ParentChangeUtils.THESAURUS;
                }
            }
        }
        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);
                }
            }
        }
        motcleImportBuilder.setNewIdalpha(newIdalpha).setParent(parentChange);
        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 ChangeRowParser newInstance(String[] fieldArray, EditThesaurusImportBuilder editThesaurusImportBuilder, ParseResultBuilder parseResultBuilder, ImportationParseContext parseContext) {
        ThesaurusColumns thesaurusColumns = ThesaurusColumns.parse(fieldArray, editThesaurusImportBuilder, parseResultBuilder);
        if ((thesaurusColumns.getIdIndex() == -1) && (thesaurusColumns.getIdalphaHandler() == null)) {
            parseResultBuilder.missingColumn(ThesaurusFieldKey.ID.toString());
            return null;
        }
        return new ChangeRowParser(editThesaurusImportBuilder, parseResultBuilder, thesaurusColumns, parseContext);
    }

}
