#ifndef SEARCHRADIUSOUTPUT_H
#define SEARCHRADIUSOUTPUT_H

#include "output.h"
#include "../recognition/searchradius.h"
#include <opencv/cv.hpp>
#include <iostream>

extern "C"
{
  #include <opencv/highgui.h>
}

using namespace std;

namespace seemicro
{

class SearchRadiusOutput : public OutputModule
{
  IplImage *maxsearch;
  SearchRadiusModule& s;
  CvFont *font;
public:
  SearchRadiusOutput(SearchRadiusModule& As, CvFont *Af) : s(As), font(Af)
  {
    if(1 != cvNamedWindow("SearchRadius", 1))
    { cerr << "cvNamedWindow(SearchRadius): error" << endl; exit(1); }

    maxsearch = cvCreateImage(cvSize(200,200), IPL_DEPTH_8U, 1);
  }

  ~SearchRadiusOutput()
  {
    cvReleaseImage(&maxsearch);
    cvDestroyWindow("SearchRadius");
  }

  void output(bool keyframe)
  {
    if(!s.outputChanged && !s.correlation.outputChanged) return;

    if(DEBUGLEVEL>=2)
      cout << "SearchRadius: Best fit for radius = " <<
       	s.best << " pixels.\n";

    cvZero(maxsearch);
    CvPoint last=cvPoint(0, 200);

    float max = 1;
    const int radiusRange=s.MAXR-s.MINR;
    for(int i=0; i<radiusRange; i++) if(s.maximazGemittelt[i]>max) max=s.maximazGemittelt[i];

    for(int i=0; i<radiusRange; i++)
    {
      CvPoint next = cvPoint(i*200/radiusRange, 200 - int(s.maximazGemittelt[i]/max*200) );
      if(next.y < 0) next.y = 5;
      if(next.y >= maxsearch->height) next.y = maxsearch->height-5;

      cvLine(maxsearch, last, next, 255);
      last = next;
    }
    char text[100];
    sprintf(text, "Radius (%i bis %i)", s.MINR, s.MAXR);
    cvPutText(maxsearch, text, cvPoint(40, 195), font, CV_RGB(255, 255, 255));
    sprintf(text, "Korrelationsstaerke");
    cvPutTextSenkrecht(maxsearch, text, cvPoint(5, 180),
       font, CV_RGB(255, 255, 255));

    // aktuell verwendeten Radius gelb einzeichnen
    int x = int((s.correlation.micro.radius-s.MINR)*200/radiusRange);
    cvLine(maxsearch, cvPoint(x,200), cvPoint(x,0), CV_RGB(255,255,0));

    cvShowImage("SearchRadius", maxsearch);
    cvResizeWindow("SearchRadius", 215, 240);

    s.outputChanged=false;
#ifdef DEBUG
    if(DEBUGLEVEL>=3) cerr << "<-SearchRadiusOutput::output()\n";
#endif
  }

}; // SearchRadiusOutput

} // seemicro

#endif

