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

import org.apache.log4j.Logger;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.dependency.IFSOAPDependencyStatement;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.dependency.IFSOAPDependency;

import java.util.Vector;

/**
 * 
 */
public class DependencyChain implements IFDependencyChain {

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

   private IFDependency rootDependency = null;

   private Vector dependencies = null;

   public DependencyChain(IFDependency rootDependency) {
      dependencies = new Vector();
      this.rootDependency = rootDependency;
      dependencies.add(rootDependency);
   }

   public boolean containsDependencyStatement(IFSOAPDependencyStatement statement) {
      boolean result = false;
      if (statement != null) {
         for (int i = 0; i < dependencies.size(); i++) {
            IFDependency dependency = (IFDependency) dependencies.elementAt(i);
            if (dependency.getReference().equals(statement.getDependency())) {
               result = true;
               break;
            }
         }
      }
      return result;
   }

   public void addDependency(IFSOAPDependency soapDependency, String newReference) {
      if(newReference != null){
         Dependency newDependency = new Dependency(newReference);
         IFSOAPDependencyStatement[] statements = soapDependency.getDependencyStatements();
         for (int i = 0; i < statements.length; i++) {
            IFSOAPDependencyStatement statement = statements[i];
            Vector dependenciesThatFit = getDependencies(statement.getDependency());
            for (int j = 0; j < dependenciesThatFit.size(); j++) {
               IFDependency dependency = (IFDependency) dependenciesThatFit.elementAt(j);
               newDependency.addReference2Dependency(dependency);
            }
         }
         if(newDependency.hasDependencies()){
            dependencies.add(newDependency);
         }
      }
   }

   private Vector getDependencies(String reference){
      Vector result = new Vector();
      for (int i = 0; i < dependencies.size(); i++) {
         IFDependency dependency = (IFDependency) dependencies.elementAt(i);
         if(dependency.getReference().equals(reference)){
            result.add(dependency);
         }
      }
      return result;
   }

   public IFDependency getRootDependency() {
      return rootDependency;
   }
}
