#include "ConditionalEstimator.h"
#include "ElInfo.h"
#include "PartitionElementData.h"
#include "Element.h"
#include "Traverse.h"
#include "mpi.h"

namespace AMDiS {

  double ConditionalEstimator::estimate(double ts) 
  {
    if(decoratedEstimator_) {

      double partition_sum = 0.0;

      elementCount_ = 0;

      decoratedEstimator_->init(ts);

      mesh = decoratedEstimator_->getMesh();
      traverseFlag = decoratedEstimator_->getTraverseFlag();

      TraverseStack stack;
      ElInfo *elInfo = stack.traverseFirst(mesh, -1, traverseFlag);
      while(elInfo) {
	PartitionElementData *elData = dynamic_cast<PartitionElementData*>
	  (elInfo->getElement()->getElementData(PARTITION_ED));

	TEST_EXIT_DBG(elInfo->getElement()->isLeaf())("element not leaf\n");
	TEST_EXIT_DBG(elData)("no partitoin data on leaf element %d (rank %d)\n", 
			      elInfo->getElement()->getIndex(),
			      MPI::COMM_WORLD.Get_rank());

	PartitionStatus status = elData->getPartitionStatus();
      
	if(status == IN || status == OVERLAP) {
	  decoratedEstimator_->estimateElement(elInfo);
	} else {
	  elInfo->getElement()->setMark(0);
	}
	elInfo = stack.traverseNext(elInfo);
      }

      elInfo = stack.traverseFirst(mesh, -1, traverseFlag);
      while(elInfo) {
	PartitionElementData *elData = dynamic_cast<PartitionElementData*>
	  (elInfo->getElement()->getElementData(PARTITION_ED));
	PartitionStatus status = elData->getPartitionStatus();
	if(status == IN) {
	  elementCount_++;
	  partition_sum += elInfo->getElement()->getEstimation(row_);
	}
	elInfo = stack.traverseNext(elInfo);
      }

      // !!! test !!!
      double total_sum = 0.0;
      MPI::COMM_WORLD.Allreduce(&partition_sum,
				&total_sum,
				1,
				MPI_DOUBLE,
				MPI_SUM);

      decoratedEstimator_->setErrorSum(total_sum);

      double total_max = 0.0;
      est_max = decoratedEstimator_->getErrorMax();
      MPI::COMM_WORLD.Allreduce(&est_max,
				&total_max,
				1,
				MPI_DOUBLE,
				MPI_MAX);

      decoratedEstimator_->setErrorMax(total_max);
    
      decoratedEstimator_->exit();

      est_sum = decoratedEstimator_->getErrorSum();
      est_max = decoratedEstimator_->getErrorMax();

      // !!! test !!!
#if 0
      decoratedEstimator_->exit();

      est_sum = sqrt(partition_sum); //decoratedEstimator_->getErrorSum();
      est_t_sum = decoratedEstimator_->getTimeEst();
      est_max = decoratedEstimator_->getErrorMax();
#endif

      //   MSG("rank %d , estimate %e (total %e) elements %d (total %d)\n", 
      //       MPI::COMM_WORLD.Get_rank(), est_sum, total_sum,
      //       elementCount_,
      //       mesh->getNumberOfLeaves());

      return est_sum;
    } else {
      return 0.0;
    }
  }

}