#ifndef PREVIEW_H
#define PREVIEW_H

#include "output.h"
#include "../recognition/imagesource.h"
#include "../recognition/videodevice.h"
#include <iostream>

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

using namespace std;

namespace seemicro
{

class PreviewOutput : public OutputModule
{
  static PreviewOutput *home;
  CvFont *font;
  int colour, hue, brightness, contrast, whiteness;
public:
  ImageSource *src;
  PreviewOutput(ImageSource *As, CvFont *Af) : font(Af), src(As)
  {
    home = this;
    if(1 != cvNamedWindow("Preview", 1))
    { cerr << "cvNamedWindow(Preview): error" << endl; exit(1); }
    try
    {
      videoDevice& v = dynamic_cast<videoDevice&>(*src);
      getPict(v);
      cvCreateTrackbar("Keyframerate", "Preview", &v.keyFrameRate, 100, callback);
      cvCreateTrackbar("Farbkontrast", "Preview", &colour, 65535, callback);
      cvCreateTrackbar("Helligkeit", "Preview", &hue, 65535, callback);
      cvCreateTrackbar("Kontrast", "Preview", &brightness, 65535, callback);
      cvCreateTrackbar("Weißpunkt", "Preview", &contrast, 65535, callback);
      cvCreateTrackbar("Farbkontrast", "Preview", &whiteness, 65535, callback);
    }
    catch(bad_cast)
    {
      // only videoDevices have these settings
    }
  }

  ~PreviewOutput()
  {
    cvDestroyWindow("Preview");
  }

  void getPict(videoDevice& v)
  {
    colour = v.pict.colour;
    hue = v.pict.hue;
    brightness = v.pict.brightness;
    contrast = v.pict.contrast;
    whiteness = v.pict.whiteness;
  }

  void setPict(videoDevice& v)
  {
    v.pict.colour = colour;
    v.pict.hue = hue;
    v.pict.brightness = brightness;
    v.pict.contrast = contrast;
    v.pict.whiteness = whiteness;
    v.setPicture(NULL);
  }

  static void callback(int dummy=0)
  {
    if(!home) return;
    try
    {
      videoDevice& v = dynamic_cast<videoDevice&>(*home->src);
      home->setPict(v);
      if(v.keyFrameRate <= 0) v.keyFrameRate=1;
   }
    catch(bad_cast)
    {
      // only videoDevices have these settings
    }
  }

  virtual void output(bool keyframe)
  {
    try
    {
      videoDevice& vdev = dynamic_cast<videoDevice&>(*src);
      double frate = vdev.framerate();// to be called for every frame
      if(keyframe)
      {
	char line[50];
	sprintf(line, "%2.1f Bilder/s", frate);
	cvPutText(src->img, line, cvPoint(src->img->width-100, 30), font,
	    CV_RGB(255, 255, 255));
      }
    }
    catch(bad_cast)
    {
      // only videoDevices have framerate()
    }
    if(keyframe)
    {
      cvShowImage("Preview", src->img);
      cvResizeWindow("Preview", src->img->width+15, src->img->height+250);
   }
  }

}; // PreviewModule

} // seemicro

#endif

