package de.tu_dresden.diplom.richter_mirko_mat2628335.witness.context;

import org.apache.log4j.Logger;

import java.util.*;

import de.tu_dresden.diplom.richter_mirko_mat2628335.common.util.ToStringUtility;
import de.tu_dresden.diplom.richter_mirko_mat2628335.witness.context.ex.ContextInfoInvalidException;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.util.ToStringUtility;

/**
 * 
 */
public class WitnessContextInfoPool {

   private static final Logger logger = Logger.getLogger(WitnessContextInfoPool.class);

   private Map contexts = null;

   public WitnessContextInfoPool() {
      contexts = new HashMap();
   }

   public synchronized void addContextInfo(IFWitnessContextInfo witnessContextInfo) throws ContextInfoInvalidException {
      if (witnessContextInfo != null) {
         contexts.put(witnessContextInfo.getContextObject().getIdentification(), witnessContextInfo);
      }
   }

   public IFWitnessContextInfo getContextInfo(String ident) {
      return (IFWitnessContextInfo) contexts.get(ident);
   }

   public synchronized void remove(IFWitnessContextInfo ctxInfo) throws ContextInfoInvalidException {
      contexts.remove(ctxInfo.getContextObject().getIdentification());
   }

   public boolean containsContextInfo(IFWitnessContextInfo ctxInfo) {
      final String fn = "[containsContextInfo] ";
      boolean result = false;
      if (ctxInfo != null) {
         Collection values = contexts.values();
         for (Iterator iterator = values.iterator(); iterator.hasNext();) {
            Object o = (Object) iterator.next();
            if (o == ctxInfo) {
               result = true;
            }
         }
      }else{
         logger.warn(fn + "context to remove is NULL!");
      }
      return result;
   }

   public String toString() {
      StringBuffer result = new StringBuffer("<WitnessContextInfoPool>\n");
      result.append(ToStringUtility.mapToString("contexts", 1, contexts));
      result.append("\n</WitnessContextInfoPool>");
      return result.toString();
   }

   protected synchronized Iterator iterate(){
      return contexts.values().iterator();
   }

   public int getManagedContextCount(){
      return contexts.size();
   }

}
