/*
 *  @author Ranides Atterwim <ranides@gmail.com>
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */

package net.ranides.assira.trace;

import java.util.Map.Entry;
import java.util.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author ranides
 */
public class LoggerStateCollection {

    private final List<String> names;

    private final Stack<Map<String, LoggerState>> stateStack = new Stack<>();

    public LoggerStateCollection(String... names) {
        this.names = new ArrayList<>();
        this.names.addAll(Arrays.asList(names));
    }

    public LoggerStateCollection(Collection<String> names) {
        this.names = new ArrayList<>();
        this.names.addAll(names);
    }

    public void push() {
        Map<String, LoggerState> snapshot = new HashMap<>();
        for (String name : names) {
            snapshot.put(name, new LoggerState(name));
        }
        stateStack.push(snapshot);
    }

    public void pop() {
        Map<String, LoggerState> snapshot = stateStack.pop();
        for(Entry<String,LoggerState> state : snapshot.entrySet()) {
            LoggerUtils.getLogger(state.getKey()).setLevel(state.getValue().getLevel());
        }
    }

    public Collection<Logger> getLoggers() {
        ArrayList<Logger> list = new ArrayList<>(stateStack.size());
        for(String name : names) {
            list.add( LoggerUtils.getLogger(name) );
        }
        return list;
    }

    public Collection<String> getLoggerNames() {
        return Collections.unmodifiableList(names);
    }

    public Level getLevel(String logger) {
        return this.stateStack.lastElement().get(logger).getLevel();
    }

    public boolean getAdditivity(String logger) {
        return this.stateStack.lastElement().get(logger).getAdditivity();
    }

    public void changeLevel(Level level) {
        for (String name : names) {
            LoggerUtils.getLogger(name).setLevel(level);
        }
    }

}
