
package de.ivu.elect.jee.presentation.dynamicform;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Named;

@Named
public class FormDataPropertyValueChangeListener implements Serializable {

  private static final long serialVersionUID = 1L;

  public FormDataPropertyValueChangeListener() {
    super();
  }

  public void onPropertyValueChanged(FormData data) {
    notifyAll(data.getProperty(), data.getObservingProperties());
  }

  public void notifyAll(Property observedProperty, Collection<Property> observingProperties) {
    notifyAllRecursive(observedProperty, observingProperties, new HashSet<>());
  }

  // Cf. de.ivu.elect.jee.presentation.dynamicform.FormData.addObservedPropertyStyleClassRecursive(Collection<String>, Collection<Property>)
  // Cf. de.ivu.elect.jee.presentation.dynamicform.FormData.addObservingPropertyStyleClassRecursive(Collection<String>, Collection<Property>)
  private void notifyAllRecursive(Property observedProperty, Collection<Property> observingProperties, Set<Property> visited) {
    observingProperties.forEach(observingProperty -> {
      observingProperty.onObservedPropertyValueChanged(observedProperty);

      // ELECTMUC-2604
      if (visited.add(observingProperty)) {
        notifyAllRecursive(observingProperty, observingProperty.getObservingProperties(), visited);
      }
    });
  }
}
