#include "Element_Tumor.h"
#include "Element_Aura.h"
namespace MFM {



  template<class CC>
  bool Element_Medicine<CC>::Fight(EventWindow<CC>& window) const{
    MDist<R>& md = MDist<R>::get();

    SPoint tumorRel;
    u32 tumorCount = 0;


    for (u32 idx = md.GetFirstIndex(1); idx <= md.GetLastIndex(1); ++idx)
    {
      const SPoint relT = md.GetPoint(idx);
      if (!window.IsLiveSite(relT))
      {
	continue;
      }
      T possibleTumor = window.GetRelativeAtom(relT);
      u32 typeT = possibleTumor.GetType();
      if(typeT == Element_Tumor<CC>::THE_INSTANCE.GetType())
      {
	++tumorCount;
	tumorRel = relT;
      }
    }
    if(tumorCount>0){

      T atom = window.GetRelativeAtom(tumorRel);
      u8 hit = Element_Tumor<CC>::THE_INSTANCE.GetAbsorb(atom);
      LOG.Debug("==>old hit(%d)",hit);
      Element_Tumor<CC>::THE_INSTANCE.SetAbsorb(atom,hit+1);
      LOG.Debug("====>new hit(%d)",hit+1);
      window.SetRelativeAtom(tumorRel,atom);
      window.SetCenterAtom(Element_Empty<CC>::THE_INSTANCE.GetDefaultAtom());
      return false;
    }
    return true;
  }

  template<class CC>
  void Element_Medicine<CC>::Move(EventWindow<CC>& window) const{
    MDist<R>& md = MDist<R>::get();
    Random & random = window.GetRandom();
    WindowScanner<CC> scanner(window);
    //const T& us = window.GetCenterAtom();
    SPoint auraRel;
    u32 auraCount = 0;


    s8 xoff = 0;
    s8 yoff = 0;

    u16 mdns = scanner.CountAtomsOfType(Element_Aura<CC>::THE_INSTANCE.GetType(),R);
    u16 ydns = 0;

    for (u32 idx = md.GetFirstIndex(1); idx <= md.GetLastIndex(R); ++idx)
    {
      const SPoint rel = md.GetPoint(idx);
      if (!window.IsLiveSite(rel))
      {
	continue;
      }
      T atom = window.GetRelativeAtom(rel);
      u32 type = atom.GetType();
      if(type == Element_Aura<CC>::THE_INSTANCE.GetType())
      {
	ydns = Element_Aura<CC>::THE_INSTANCE.GetDense(atom);
	if (mdns>=ydns){}
	else{
	  mdns=ydns;
	  xoff = rel.GetX();
	  yoff = rel.GetY();
	  ++auraCount;
	  auraRel = rel;
	}
      }
    }
    //u16 mdns = scanner.CountAtomsOfType(Element_Aura<CC>::THE_INSTANCE.GetType(),R);
    T me = window.GetCenterAtom();
    SetAid(me,mdns);
    window.SetCenterAtom(me);
    /*if(random.OneIn(2)){
      this->Sneak(window);
    }else{
      SetXLoc(me,0);
      SetYLoc(me,0);
      window.SetCenterAtom(me);
      this->Diffuse(window);
    }*/
    if(auraCount>0){
      if(random.OneIn(2)){
	SetXLoc(me,xoff);
	SetYLoc(me,yoff);
	window.SetCenterAtom(me);
	window.SwapAtoms(auraRel,SPoint(0,0));
      }
    }
    else{
      if(random.OneIn(2)){
	this->Sneak(window);
      }else{
	SetXLoc(me,0);
	SetYLoc(me,0);
	window.SetCenterAtom(me);
	this->Diffuse(window);
      }
    }
  }
}
