/*************************************************************************
 *    CompuCell - A software framework for multimodel simulations of     *
 * biocomplexity problems Copyright (C) 2003 University of Notre Dame,   *
 *                             Indiana                                   *
 *                                                                       *
 * This program is free software; IF YOU AGREE TO CITE USE OF CompuCell  *
 *  IN ALL RELATED RESEARCH PUBLICATIONS according to the terms of the   *
 *  CompuCell GNU General Public License RIDER you can redistribute it   *
 * and/or modify it under the terms of the GNU General Public License as *
 *  published by the Free Software Foundation; either version 2 of the   *
 *         License, or (at your option) any later version.               *
 *                                                                       *
 * This program is distributed in the hope that it will be useful, but   *
 *      WITHOUT ANY WARRANTY; without even the implied warranty of       *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    *
 *             General Public License for more details.                  *
 *                                                                       *
 *  You should have received a copy of the GNU General Public License    *
 *     along with this program; if not, write to the Free Software       *
 *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.        *
 *************************************************************************/

#include "ContactEnergy.h"

#include <CompuCell3D/Field3D/Field3D.h>
#include <CompuCell3D/Potts3D/Potts3D.h>
#include <CompuCell3D/Potts3D/Cell.h>
#include <CompuCell3D/Automaton/Automaton.h>
using namespace CompuCell3D;

#include <XMLCereal/XMLPullParser.h>
#include <XMLCereal/XMLSerializer.h>

#include <BasicUtils/BasicString.h>
#include <BasicUtils/BasicException.h>

#include <CompuCell3D/Potts3D/Cell.h>

#include <algorithm>


#include <string>
using namespace std;

double ContactEnergy::localEnergy(const Point3D &pt) {
  return 0;
}

//double ContactEnergy::changeEnergy(const Point3D &pt,
//                                  const Cell *newCell,
//                                   const Cell *oldCell) {
//
//   double energy = 0;
//   unsigned int token = 0;
//   double distance = 0;
//   Point3D n;
//   Cell *nCell;
//   Field3D<Cell *> *field = potts->getCellField();
//   
//   while (true) {
//     n = field->getNeighbor(pt, token, distance, false);
//     if (distance > depth) break;
// 
//     nCell = field->get(n);
// 
//     energy -= contactEnergy(oldCell, nCell) / distance;
//     energy += contactEnergy(newCell, nCell) / distance;
//   }
// 
//   return energy;
// }

double ContactEnergy::changeEnergy(const Point3D &pt,
                                  const CellG *newCell,
                                  const CellG *oldCell) {
   //cerr<<"ChangeEnergy"<<endl;
   
   
  double energy = 0;
  unsigned int token = 0;
  double distance = 0;
  Point3D n;
  
  CellG *nCell=0;
  Field3D<CellG *> *fieldG = potts->getCellFieldG();
     
  while (true) {
    n = fieldG->getNeighbor(pt, token, distance, false);
    if (distance > depth) break;

    nCell = fieldG->get(n);
    
    energy -= contactEnergy(oldCell, nCell) / distance;
    energy += contactEnergy(newCell, nCell) / distance;
  }
/*  if(fabs(energy)>1.0){
   cerr<<"ChangeEnergy before return "<<energy<<endl;
  }*/
  return energy;
}

double ContactEnergy::contactEnergy(const CellG *cell1, const CellG *cell2) {
   
   return contactEnergyArray[cell1 ? cell1->type : 0][cell2? cell2->type : 0];


}

void ContactEnergy::setContactEnergy(const string typeName1,
				     const string typeName2,
				     const double energy) {
                    
  char type1 = automaton->getTypeId(typeName1);
  char type2 = automaton->getTypeId(typeName2);
    
  int index = getIndex(type1, type2);

  contactEnergies_t::iterator it = contactEnergies.find(index);
  ASSERT_OR_THROW(string("Contact energy for ") + typeName1 + " " + typeName2 +
		  " already set!", it == contactEnergies.end());

  contactEnergies[index] = energy;
}

int ContactEnergy::getIndex(const int type1, const int type2) const {
  if (type1 < type2) return ((type1 + 1) | ((type2 + 1) << 16));
  else return ((type2 + 1) | ((type1 + 1) << 16));
}


void ContactEnergy::readXML(XMLPullParser &in) {
  in.skip(TEXT);

   automaton = potts->getAutomaton();
   set<unsigned char> cellTypesSet;
   
  while (in.check(START_ELEMENT)) {
    if (in.getName() == "Energy") {
      string type1 = in.getAttribute("Type1").value;
      string type2 = in.getAttribute("Type2").value;

      double energy = BasicString::parseDouble(in.matchSimple());
      setContactEnergy(type1, type2, energy);

      //inserting all the types to the set (duplicate are automatically eleminated) to figure out max value of type Id
      cellTypesSet.insert(automaton->getTypeId(type1));
      cellTypesSet.insert(automaton->getTypeId(type2));
    } 
    else if (in.getName() == "Depth") {
      depth = BasicString::parseDouble(in.matchSimple());
      
    } else {
      throw BasicException(string("Unexpected element '") + in.getName() +
                           "'!", in.getLocation());
    }

    in.skip(TEXT);
  }

  //Now that we know all the types used in the simulation we will find size of the contactEnergyArray
  vector<unsigned char> cellTypesVector(cellTypesSet.begin(),cellTypesSet.end());//coping set to the vector

  int size= * max_element(cellTypesVector.begin(),cellTypesVector.end());
  size+=1;//if max element is e.g. 5 then size has to be 6 for an array to be properly allocated
  
  int index ;
  contactEnergyArray.assign(size,vector<double>(size,0.0));

  for(int i = 0 ; i < size ; ++i)
   for(int j = 0 ; j < size ; ++j){
   
      index = getIndex(cellTypesVector[i],cellTypesVector[j]);
      
      contactEnergyArray[i][j] = contactEnergies[index];
      
   }
   cerr<<"size="<<size<<endl;
   
  for(int i = 0 ; i < size ; ++i)
   for(int j = 0 ; j < size ; ++j){
   
      cerr<<"contact["<<i<<"]["<<j<<"]="<<contactEnergyArray[i][j]<<endl;
      
   }
   
//   exit(0);
}

void ContactEnergy::writeXML(XMLSerializer &out) {
}
