package de.ivu.elect.jee.faces.componentcount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import javax.faces.component.UIComponent;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitResult;

public class CountingVisitCallback implements VisitCallback {

  private int count = 0;

  private List componentInfo = new ArrayList();

  public Map<String, AtomicLong> getCountPerType() {
    return countPerType;
  }

  private Map<String, AtomicLong> countPerType = new HashMap<>();

  /**
   * This method will be invoked on every node of the component tree.
   */
  @Override
  public VisitResult visit(VisitContext context, UIComponent target) {

    count++;

    String simpleName = target.getClass().getSimpleName();
    if (!countPerType.containsKey(simpleName)) {
      countPerType.put(simpleName, new AtomicLong(0L));
    }
    countPerType.get(simpleName).addAndGet(1L);
    getComponentInfo().add(target.getClientId() + " [" + simpleName + "]");

//    if ("UIInstructions".equals(simpleName)) {
//      System.out.println("UIInstructions: " + target);
//
//    }

    // descend into current subtree, if applicable
    return VisitResult.ACCEPT;
  }

  public int getCount() {
    return count;
  }

  public List getComponentInfo() {
    return componentInfo;
  }

}