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

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

import javax.faces.component.visit.VisitContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ComponentCounter implements PhaseListener {

  private static final long serialVersionUID = 8573925562596090327L;

  private static final Logger LOG = LoggerFactory.getLogger(ComponentCounter.class);

  @Override
  public void beforePhase(PhaseEvent event) {

// nichts zu tun

  }

  @Override
  public PhaseId getPhaseId() {
    return PhaseId.RENDER_RESPONSE;
  }

  @Override
  public void afterPhase(PhaseEvent event) {
    FacesContext facesContext = event.getFacesContext();
    VisitContext visitContext = VisitContext.createVisitContext(facesContext);

    CountingVisitCallback callback = new CountingVisitCallback();
    facesContext.getViewRoot().visitTree(visitContext, callback);

    LOG.info("After Number of Components: " + callback.getCount());

    List<Map.Entry<String, AtomicLong>> sorted = new ArrayList<>(callback.getCountPerType().entrySet());
    Collections.sort(sorted, (o1, o2) -> Long.compare(o2.getValue().get(), o1.getValue().get()));

    for (Map.Entry<String, AtomicLong> entry :sorted) {
      LOG.info("Anzahl: " + entry.getValue() + " - Class: " + entry.getKey());
    }

  }
}
