/*                                              -*- mode:C++ -*-
  Element_Cell_Wall.h Wall cell element
  Copyright (C) 2014 The Regents of the University of New Mexico.  All rights reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  USA
*/

/**
  \file Element_Cell_Wall.h Wall cell element
  \author Trent R. Small.
  \author Xinu Chen.
  \date (C) 2014 All rights reserved.
  \lgpl
 */
#ifndef ELEMENT_CELL_WALL_H
#define ELEMENT_CELL_WALL_H

#include "Element.h"
#include "EventWindow.h"
#include "ElementTable.h"
#include "itype.h"
#include "P3Atom.h"

namespace MFM
{

#define CELL_VERSION 1

  template <class CC>
  class Element_Cell_Wall : public Element<CC>
  {
    // Extract short names for parameter types
    typedef typename CC::ATOM_TYPE T;
    typedef typename CC::PARAM_CONFIG P;
    enum
    {
      R = P::EVENT_WINDOW_RADIUS,
      BITS = P::BITS_PER_ATOM,

      TIMER_POS = P3Atom<P>::P3_STATE_BITS_POS,
      TIMER_LEN = 32,

      X_LOC_POS = TIMER_POS + TIMER_LEN,
      X_LOC_LEN = 8,

      Y_LOC_POS = X_LOC_POS + X_LOC_LEN,
      Y_LOC_LEN = 8
    };

    typedef BitField<BitVector<BITS>, TIMER_LEN, TIMER_POS> AFTimer;
    typedef BitField<BitVector<BITS>, X_LOC_LEN, X_LOC_POS> AFXLoc;
    typedef BitField<BitVector<BITS>, Y_LOC_LEN, Y_LOC_POS> AFYLoc;

  public:
    u32 GetTimer(const T& us) const
    {
      return AFTimer::Read(this->GetBits(us));
    }

    void SetTimer(T& us, const u32 timer) const
    {
      AFTimer::Write(this->GetBits(us), timer);
    }

    s8 GetXLoc(const T& us) const
    {
      return (s8)AFXLoc::Read(this->GetBits(us));
    }

    void SetXLoc(T& us, const s8 xloc) const
    {
      AFXLoc::Write(this->GetBits(us), xloc);
    }

    s8 GetYLoc(const T& us) const
    {
      return AFYLoc::Read(this->GetBits(us));
    }

    void SetYLoc(T& us, const s8 timer) const
    {
      AFYLoc::Write(this->GetBits(us), timer);
    }

    void SetLoc(T& us, const SPoint& loc) const
    {
      //u8 xLoc = (loc.GetX() & 0x7f) * (loc.GetX() > 0 ? 1 : -1);
      //u8 yLoc = (loc.GetY() & 0x7f) * (loc.GetY() > 0 ? 1 : -1);
      SetXLoc(us, (s8)loc.GetX());
      SetYLoc(us, (s8)loc.GetY());
    }

    void FillLoc(SPoint& pt, const T& us) const
    {
      pt.Set(GetXLoc(us), GetYLoc(us));
    }

    /**
     * returns true if timer == 0
     */
    bool DecrementTimer(T& us) const
    {
      u32 timerVal = GetTimer(us);
      if(timerVal == 0)
      {
	timerVal = 1;
      }
      SetTimer(us, timerVal - 1);

      return timerVal == 1;
    }

    static Element_Cell_Wall THE_INSTANCE;
    static const u32 TYPE()
    {
      return THE_INSTANCE.GetType();
    }

    Element_Cell_Wall()
      : Element<CC>(MFM_UUID_FOR("CellWall", CELL_VERSION))
    {
      Element<CC>::SetAtomicSymbol("Cw");
      Element<CC>::SetName("CellWall");
    }

    virtual const T & GetDefaultAtom() const
    {
      static T defaultAtom(TYPE(),0,0,0);

      return defaultAtom;
    }

    virtual u32 PercentMovable(const T& you,
                               const T& me, const SPoint& offset) const
    {
      return 0;
    }

    virtual u32 DefaultPhysicsColor() const
    {
      return 0xffffffff;
    }

    virtual u32 DefaultLowlightColor() const
    {
      return 0xff7f7f7f;
    }

    virtual void Behavior(EventWindow<CC>& window) const
    {
      T copyUs = window.GetCenterAtom();
      MDist<R>& md = MDist<R>::get();
      bool allNeighborsSameDistance = true;
      bool isNeighborFurther = false;

      if(DecrementTimer(copyUs))
      {
	window.SetCenterAtom(Element_Empty<CC>::THE_INSTANCE.GetDefaultAtom());
	return;
      }
      else
      {
	window.SetCenterAtom(copyUs);
      }

      const T& us = window.GetCenterAtom();

      for(u32 i = md.GetFirstIndex(1); i <= md.GetLastIndex(R); i++)
      {
	SPoint pt = md.GetPoint(i);
	const T& neighbor = window.GetRelativeAtom(pt);

	if(TYPE() == neighbor.GetType())
	{
	  SPoint neighborLoc;
	  SPoint myLoc;
	  FillLoc(neighborLoc, neighbor);
	  FillLoc(myLoc, us);
	  if(neighborLoc.GetManhattanLength() !=
	     myLoc.GetManhattanLength())
	  {
	    allNeighborsSameDistance = false;
	    if(neighborLoc.GetManhattanLength() >
	       myLoc.GetManhattanLength())
	    {
	      isNeighborFurther = true;
	    }
	  }
	}
      }

      if(allNeighborsSameDistance || isNeighborFurther)
      {
	Grow(window);
      }
    }

  private:

    void Grow(EventWindow<CC>& window) const
    {
      const T us = window.GetCenterAtom();
      SPoint ourLoc;
      u32 ourDist;
      MDist<R>& md = MDist<R>::get();

      FillLoc(ourLoc, us);
      ourDist = ourLoc.GetManhattanLength();

      for(u32 i = md.GetFirstIndex(1); i <= md.GetLastIndex(R); i++)
      {
	SPoint pt = md.GetPoint(i);
	SPoint possiblePt = ourLoc + pt;

	if(window.GetRelativeAtom(pt).GetType() ==
	   Element_Empty<CC>::THE_INSTANCE.GetType())
	{
	  if(possiblePt.GetManhattanLength() < 128)
	  {
	    if(possiblePt.GetManhattanLength() == ourDist + 1)
	    {
	      T wall = GetDefaultAtom();
	      SetTimer(wall, GetTimer(us));
	      SetLoc(wall, possiblePt);

	      window.SetRelativeAtom(pt, wall);
	    }
	  }
	}
      }
      window.SetCenterAtom(Element_Empty<CC>::THE_INSTANCE.GetDefaultAtom());
    }
  };

  template <class CC>
  Element_Cell_Wall<CC> Element_Cell_Wall<CC>::THE_INSTANCE;

}

#endif /* ELEMENT_CELL_WALL_H */
