#include "RSGraphBased.h"

#include <iostream>
#include <fstream>

#ifdef NICE_USELIB_OPENMP
#include <omp.h>
#endif

#include "felzenszwalb/image.h"
#include "felzenszwalb/misc.h"
#include "felzenszwalb/segment-image.h"
#include "felzenszwalb/pnmfile.h"

using namespace std;
using namespace NICE;
using namespace OBJREC;
using namespace felzenszwalb;

///////////////////// ///////////////////// /////////////////////
//                   CONSTRUCTORS / DESTRUCTORS
///////////////////// ///////////////////// /////////////////////

RSGraphBased::RSGraphBased() : RegionSegmentationMethod()
{
  this->parameter_k = 500;
  this->parameter_min_size = 200;
  this->parameter_sigma = 1.5;
}

RSGraphBased::RSGraphBased( const NICE::Config * _conf )
{
  this->initFromConfig ( _conf );  
}

RSGraphBased::~RSGraphBased()
{
}

void RSGraphBased::initFromConfig( const NICE::Config* _conf, const std::string & _confSection )
{
  //thr = _conf->gD( _confSection, "threshold", 5.0);
  this->parameter_k        = _conf->gD(_confSection, "k",        500);
  this->parameter_min_size = _conf->gI(_confSection, "min_size", 200);
  this->parameter_sigma    = _conf->gD(_confSection, "sigma",    1.5);
}



///////////////////// ///////////////////// /////////////////////
//                      SEGMENTATION STUFF
///////////////////// ///////////////////// //////////////////

int RSGraphBased::segRegions ( const NICE::Image & img, NICE::Matrix & mask) const
{
  NICE::ColorImage cimg(img, img, img);
  return segRegions(cimg, mask);
}

int RSGraphBased::segRegions ( const NICE::ColorImage & img, NICE::Matrix & mask) const
{
  const unsigned int imageWidth  = img.width();
  const unsigned int imageHeight = img.height();

  // Kopieren der Werte aus dem ColorImage -> image<rgb>

  image<rgb> *inputImage = new image<rgb>( imageWidth, imageHeight, false );

#pragma omp parallel for
  for ( unsigned int y = 0; y < imageHeight; y++ )
  {
    for ( unsigned int x = 0; x < imageWidth; x++ )
    {
      imRef( inputImage, x, y ).r = img.getPixelQuick( x, y, 0 );
      imRef( inputImage, x, y ).g = img.getPixelQuick( x, y, 1 );
      imRef( inputImage, x, y ).b = img.getPixelQuick( x, y, 2 );
    }
  }


  // Eingabebild segmentieren
  int num_ccs; // Anzahl der segmentierten Regionen
  image<rgb> *tempResultImage = segment_image( inputImage, parameter_sigma, parameter_k, parameter_min_size, &num_ccs );

  // Kopieren der Werte aus dem image<rgb> -> ColorImage
  NICE::ColorImage resultImage( imageWidth, imageHeight );

#pragma omp parallel for
  for ( unsigned int y = 0; y < imageHeight; y++ )
  {
    for ( unsigned int x = 0; x < imageWidth; x++ )
    {
      resultImage.setPixelQuick( x, y, 0, imRef(tempResultImage, x, y ).r );
      resultImage.setPixelQuick( x, y, 1, imRef(tempResultImage, x, y ).g );
      resultImage.setPixelQuick( x, y, 2, imRef(tempResultImage, x, y ).b );
    }
  }

  // Speicher freigeben
  delete inputImage;
  inputImage = NULL;
  delete tempResultImage;
  tempResultImage = NULL;

  transformSegmentedImg( resultImage, mask);

  return num_ccs;
}

///////////////////// INTERFACE PERSISTENT /////////////////////
// interface specific methods for store and restore
///////////////////// INTERFACE PERSISTENT ///////////////////// 

void RSGraphBased::restore ( std::istream & is, int format )
{
  //delete everything we knew so far...
  this->clear();
  
  
  if ( is.good() )
  {
    
    std::string tmp;
    is >> tmp; //class name 
    
    if ( ! this->isStartTag( tmp, "RSGraphBased" ) )
    {
      std::cerr << " WARNING - attempt to restore RSGraphBased, but start flag " << tmp << " does not match! Aborting... " << std::endl;
      throw;
    }   
    
    bool b_endOfBlock ( false ) ;
    
    while ( !b_endOfBlock )
    {
      is >> tmp; // start of block 
      
      if ( this->isEndTag( tmp, "RSGraphBased" ) )
      {
        b_endOfBlock = true;
        continue;
      }      
      
      tmp = this->removeStartTag ( tmp );    
     
      if ( tmp.compare("parameter_k") == 0 )
      {
        is >> this->parameter_k;
        is >> tmp; // end of block 
        tmp = this->removeEndTag ( tmp );
      }
      else if ( tmp.compare("parameter_min_size") == 0 )
      {
        is >> this->parameter_min_size;
        is >> tmp; // end of block 
        tmp = this->removeEndTag ( tmp );
      }      
      else if ( tmp.compare("parameter_sigma") == 0 )
      {
        is >> this->parameter_sigma;
        is >> tmp; // end of block 
        tmp = this->removeEndTag ( tmp );
      }
      else
      {
      std::cerr << "WARNING -- unexpected RSGraphBased object -- " << tmp << " -- for restoration... aborting" << std::endl;
      throw;
      }
    }
  }
  else
  {
    std::cerr << "RSGraphBased::restore -- InStream not initialized - restoring not possible!" << std::endl;
    throw;
  }
}

void RSGraphBased::store ( std::ostream & os, int format ) const
{ 
  if (os.good())
  {
    // show starting point
    os << this->createStartTag( "RSGraphBased" ) << std::endl;    

    os << this->createStartTag( "parameter_k" ) << std::endl;
    os << this->parameter_k << std::endl;
    os << this->createEndTag( "parameter_k" ) << std::endl;
    
    os << this->createStartTag( "parameter_min_size" ) << std::endl;
    os << this->parameter_min_size << std::endl;
    os << this->createEndTag( "parameter_min_size" ) << std::endl;  

    os << this->createStartTag( "parameter_sigma" ) << std::endl;
    os << this->parameter_sigma << std::endl;
    os << this->createEndTag( "parameter_sigma" ) << std::endl;  
    
    // done
    os << this->createEndTag( "RSGraphBased" ) << std::endl;    
  }
  else
  {
    std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  }
}

void RSGraphBased::clear ()
{
  //TODO
}