/* FichothequeLib_Tools - Copyright (c) 2018-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.handlers;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.fichotheque.Fichotheque;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.Subset;
import net.fichotheque.SubsetKey;
import net.fichotheque.include.IncludeKey;
import net.fichotheque.tools.importation.ParseResultBuilder;
import net.fichotheque.tools.importation.parsers.Row;
import net.fichotheque.tools.importation.parsers.TiesParser;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public class JunctionHandlers {

    private final boolean replaceDefault;
    private final boolean allowLiage;
    private final List<InternalJunctionHandler> list = new ArrayList<InternalJunctionHandler>();
    private final Map<IncludeKey, InternalJunctionHandler> map = new HashMap<IncludeKey, InternalJunctionHandler>();
    private InternalJunctionHandler liageJunctionHandler;

    public JunctionHandlers(boolean replaceDefault, boolean allowLiage) {
        this.replaceDefault = replaceDefault;
        this.allowLiage = allowLiage;
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public void handle(Row row, TiesParser tiesParser) {
        for (InternalJunctionHandler junctionHandler : list) {
            junctionHandler.handle(row, tiesParser);
        }
    }

    public boolean testJunctionHandlerCandidate(Fichotheque fichotheque, String field, int index, ParseResultBuilder parseResultBuilder) {
        int idx = field.indexOf("!");
        boolean replace = replaceDefault;
        boolean idalphaOnly = false;
        if (idx > 0) {
            String params = field.substring(idx + 1);
            field = field.substring(0, idx);
            String[] tokens = StringUtils.getTokens(params, ',', StringUtils.EMPTY_EXCLUDE);
            for (String token : tokens) {
                switch (token) {
                    case "append":
                        replace = false;
                        break;
                    case "replace":
                        replace = true;
                        break;
                    case "idalpha":
                        idalphaOnly = true;
                        break;
                }
            }
        }
        InternalJunctionHandler junctionHandler;
        try {
            IncludeKey includeKey = IncludeKey.parse(field);
            SubsetKey subsetKey = includeKey.getSubsetKey();
            Subset subset = fichotheque.getSubset(subsetKey);
            if (subset == null) {
                parseResultBuilder.unknownSubset(includeKey.getKeyString());
                return true;
            }
            junctionHandler = getOrCreate(includeKey);
        } catch (ParseException pe) {
            if (field.equals(FichothequeConstants.LIAGE_NAME)) {
                if (!allowLiage) {
                    parseResultBuilder.notAvailableColumn(field);
                    return true;
                }
                if (liageJunctionHandler == null) {
                    liageJunctionHandler = new InternalJunctionHandler();
                    list.add(liageJunctionHandler);
                }
                junctionHandler = liageJunctionHandler;
            } else {
                return false;
            }
        }
        if (replace) {
            junctionHandler.setReplace(true);
        }
        if (idalphaOnly) {
            junctionHandler.setIdalphaOnly(true);
        }
        junctionHandler.addIndex(index);
        return true;
    }

    private InternalJunctionHandler getOrCreate(IncludeKey includeKey) {
        InternalJunctionHandler junctionHandler = map.get(includeKey);
        if (junctionHandler == null) {
            junctionHandler = new InternalJunctionHandler(includeKey);
            list.add(junctionHandler);
            map.put(includeKey, junctionHandler);
        }
        return junctionHandler;
    }


    private static class InternalJunctionHandler {

        private final boolean isLiage;
        private final IncludeKey includeKey;
        private final List<Integer> indexList = new ArrayList<Integer>();
        private boolean replace = false;
        private boolean idalphaOnly = false;

        private InternalJunctionHandler(IncludeKey includeKey) {
            this.includeKey = includeKey;
            this.isLiage = false;
        }

        private InternalJunctionHandler() {
            this.isLiage = true;
            this.includeKey = null;
        }

        private void setReplace(boolean replace) {
            this.replace = replace;
        }

        private void setIdalphaOnly(boolean idalphaOnly) {
            this.idalphaOnly = idalphaOnly;
        }

        private void handle(Row row, TiesParser tiesParser) {
            if (replace) {
                if (!isLiage) {
                    tiesParser.addRemovedIncludeKey(includeKey);
                }
            }
            int columnCount = row.getColumnCount();
            if (indexList.size() == 1) {
                int index = indexList.get(0);
                if (index < columnCount) {
                    if (isLiage) {
                        tiesParser.addLiage(Collections.singletonList(cleanValue(row, index)), replace);
                    } else {
                        tiesParser.add(includeKey, Collections.singletonList(cleanValue(row, index)), replace, idalphaOnly);
                    }
                }
            } else {
                List<String> stringList = new ArrayList();
                for (Integer index : indexList) {
                    if (index < columnCount) {
                        stringList.add(cleanValue(row, index));
                    }
                }
                if (isLiage) {
                    tiesParser.addLiage(stringList, replace);
                } else {
                    tiesParser.add(includeKey, stringList, replace, idalphaOnly);
                }
            }
        }

        private void addIndex(int index) {
            indexList.add(index);
        }

        private String cleanValue(Row row, int index) {
            String value = row.getColumnValue(index);
            int length = value.length();
            if (length == 0) {
                return value;
            }
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < length; i++) {
                char carac = value.charAt(i);
                switch (carac) {
                    case '\u00A0':
                    case '\u2007':
                    case '\u202F':
                        buf.append(' ');
                        break;
                    default:
                        buf.append(carac);
                }
            }
            return buf.toString();
        }

    }

}
