/*****************************************************************/
/**@file CameraTools.h: 
 * Desctiption: Higher level abstraction prototypes above raw    *
 *              camera driver.*					 *
 * Dependency:						  	 *
 *****************************************************************/
#ifndef _CAMERA_TOOLS_H_INCLUDED_
#define _CAMERA_TOOLS_H_INCLUDED_

#include <vector>

#include "points.h"
#include "images/ras_prot.h"


class CamImage: public Raster2D_8Bit
{
public:
  inline void CheckX(int & XVal)     ///< Ensure proper range that fits horizontally
    {if(XVal<0) XVal=0; if(XVal>=Size1D) XVal=Size1D-1;}
  inline void CheckY(int & YVal)     ///< Ensure proper range that fits vertically
    {if(YVal<0) YVal=0; if(YVal>=Size2D) YVal=Size2D-1;}

  inline bool iswhite(int x, int y)
	{return(GetValue2D(x,y)!=0);}
};


/** Wrapper around camera grabber - suport for ball searching */
class CameraTool: public AdDriver
{
private:  
  DoublePoint VideoX;		///< Detected X video coordinate
  DoublePoint VideoY;		///< Detected Y video coordinate

  unsigned char threshold;	///< Threshold for image detection

  ByteWrapPoint WrThreshold;    ///< External access to threshold through point interface
  CamImage IntImage;		///< Internal buffer for ball detector  

  int iWidth, iHeight;

public:
  CameraTool(void):lastx(120), lasty(120), found(false),
                   Camera(NULL), threshold(DEFAULT_THR),
		   WrThreshold(&threshold)	{BalSearchAlloved=false;} ///< default constructor
  
  //bool ReadImageAs(std::vector<unsigned char> & ImageData, int mode);
  bool ReadImageAs(Raster2DAbstract *ImageBuf, int mode, bool VFlip, bool HFlip, const unsigned char *BufferData);

  CameraDevice *Camera;
  int GetWidth(void) {return iWidth;}		///< transformed width
  int GetHeight(void) {return iHeight;}	        ///< transformed height
    
// Interface AdDriver
  Point *GetInput(int Index);	                ///< all points are accessible through this interface

  static const int DEFAULT_THR;			///< Default threshold value

private:
	// ball search status variables
  bool found;
  int lastx, lasty, expx, expy;
  	
public:    
  bool BalSearchAlloved;

  DoublePoint *GetVideoX(void) {return &VideoX;}
  DoublePoint *GetVideoY(void) {return &VideoY;}
  virtual int Execute(void);
  void InvalidateVideoPos(void);

  /**Set a threshold value */
  void SetThreshold(unsigned char New_thr) {threshold=New_thr;}  
  unsigned char GetThreshold(void)  ///< Read a threshold value 
	{return(threshold);};

  enum BALLSTATE
  {
    BALL_OK,
    BALL_NONE,
    BALL_BIG,
    BALL_FAIL
  };

  BALLSTATE BallSearch(int* x, int* y, bool VFlip, bool HFlip); ///< Get a position of a circle.
};

#endif // _CAMERA_TOOLS_H_INCLUDED_