/* UtilLib - 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.mapeadores.util.logging;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.mapeadores.util.localisation.Message;


/**
 *
 * @author Vincent Calame
 */
public class SourceLogsBuilder implements MultiMessageHandler {

    private final Map<String, SourceLogBuilder> builderMap = new LinkedHashMap<String, SourceLogBuilder>();
    private SourceLogBuilder currentBuffer = null;

    public SourceLogsBuilder() {
    }

    @Override
    public void setCurrentSource(String sourceName) {
        SourceLogBuilder builder = builderMap.get(sourceName);
        if (builder == null) {
            builder = new SourceLogBuilder(sourceName);
            builderMap.put(sourceName, builder);
        }
        currentBuffer = builder;
    }

    @Override
    public void addMessage(String category, Message message) {
        if (currentBuffer == null) {
            setCurrentSource("");
        }
        currentBuffer.addMessage(category, message);
    }

    public SourceLogs toSourceLogs() {
        List<SourceLog> tempList = new ArrayList<SourceLog>();
        for (SourceLogBuilder builder : builderMap.values()) {
            SourceLog log = builder.toSourceLog();
            if (!log.isEmpty()) {
                tempList.add(log);
            }
        }
        return new InternalSourceLogs(tempList.toArray(new SourceLog[tempList.size()]));
    }


    private static class InternalSourceLogs extends AbstractList<SourceLog> implements SourceLogs {

        private final SourceLog[] array;

        private InternalSourceLogs(SourceLog[] array) {
            this.array = array;
        }

        @Override
        public int size() {
            return array.length;
        }

        @Override
        public SourceLog get(int i) {
            return array[i];
        }

    }

}
