/* FichothequeLib_Tools - Copyright (c) 2018-2023 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.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.LiensParser;
import net.fichotheque.tools.importation.parsers.Row;
import net.mapeadores.util.text.StringUtils;


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

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

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

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

    public void handle(Row row, LiensParser liensParser) {
        for (InternalCroisementHandler croisementHandler : list) {
            croisementHandler.handle(row, liensParser);
        }
    }

    public boolean testCroisementHandlerCandidate(Fichotheque fichotheque, String field, int index, ParseResultBuilder parseResultBuilder) {
        int idx = field.indexOf("!");
        boolean replace = replaceDefault;
        boolean idalpha = 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":
                        idalpha = true;
                        break;
                }
            }
        }
        InternalCroisementHandler croisementHandler;
        try {
            IncludeKey includeKey = IncludeKey.parse(field);
            SubsetKey subsetKey = includeKey.getSubsetKey();
            Subset subset = fichotheque.getSubset(subsetKey);
            if (subset == null) {
                parseResultBuilder.unknownSubset(includeKey.getKeyString());
                return true;
            }
            croisementHandler = getOrCreate(includeKey);
        } catch (ParseException pe) {
            if (field.equals(FichothequeConstants.LIAGE_NAME)) {
                if (!allowLiage) {
                    parseResultBuilder.notAvailableColumn(field);
                    return true;
                }
                if (liageCroisementHandler == null) {
                    liageCroisementHandler = new InternalCroisementHandler(null);
                    list.add(liageCroisementHandler);
                }
                croisementHandler = liageCroisementHandler;
            } else {
                return false;
            }
        }
        if (replace) {
            croisementHandler.setReplace(true);
        }
        if (idalpha) {
            croisementHandler.setIdalpha(true);
        }
        croisementHandler.addIndex(index);
        return true;
    }

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


    private static class InternalCroisementHandler {

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

        private InternalCroisementHandler(IncludeKey includeKey) {
            this.includeKey = includeKey;
        }

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

        private void setIdalpha(boolean idalpha) {
            this.idalpha = idalpha;
        }

        private void handle(Row row, LiensParser liensParser) {
            if (replace) {
                if (includeKey == null) {
                    liensParser.checkReplaceLiage();
                } else {
                    liensParser.checkReplaceIncludeKey(includeKey);
                }
            }
            int columnCount = row.getColumnCount();
            if (indexList.size() == 1) {
                int index = indexList.get(0);
                if (index < columnCount) {
                    if (includeKey == null) {
                        liensParser.addLiage(row.getColumnValue(index), replace);
                    } else {
                        liensParser.add(includeKey, row.getColumnValue(index), replace, idalpha);
                    }
                }
            } else {
                List<String> stringList = new ArrayList();
                for (Integer index : indexList) {
                    if (index < columnCount) {
                        stringList.add(row.getColumnValue(index));
                    }
                }
                if (includeKey == null) {
                    liensParser.addLiage(stringList, replace);
                } else {
                    liensParser.add(includeKey, stringList, replace, idalpha);
                }
            }
        }

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

    }

}
