#include "funkce.h"

void show_image(my_image * img){
    IplImage * img_s=img->get_cv_image();
    cvShowImage("mainWin", img_s);
    cvWaitKey(0);
    cvDestroyWindow("mainWin");
    cvReleaseImage(&img_s);
}
void save_image(my_image * img,char * name){
    IplImage * img_s=img->get_cv_image();
    cvSaveImage(name,img_s);
    cvReleaseImage(&img_s);
}

void show_point_on_image(my_image * img,std::vector<BOD> body,int size){
    IplImage * img_s=img->get_cv_image();
    CvPoint pt1, pt2;
    int half=size/2;
    CvScalar color=cvScalar(0,0,255);

    std::vector<BOD>::iterator it;
    for(it=body.begin();it!=body.end();it++)
    {
        pt1.x = it->x-half;
        pt1.y = it->y-half;

        pt2.x = it->x+half;
        pt2.y = it->y+half;
        if(it==body.begin()+3){
            color.val[2]=0;
            color.val[1]=255;
        }
        if(it==body.begin()+6){
            color.val[0]=255;
            color.val[1]=0;
        }
        cvRectangle( img_s, pt1, pt2, color, 1, 8, 0 );
        std::cout<<"bod x "<<it->x<<" y "<<it->y<<" value "<<it->val<<"\n";

    }

    cvNamedWindow( "body" );

    cvSetMouseCallback( "body", my_mouse_callback_write_pixel, (void*) img_s);

    cvShowImage("body", img_s);
    cvWaitKey(0);
    cvDestroyWindow("body");
    cvReleaseImage(&img_s);
}


bool BOD::operator<(const BOD &druhy) const
{
   return this->val<druhy.val;
}



my_image * edge(my_image * img,double t1,double t2,int size){
    IplImage *src=img->get_cv_image();
    IplImage * dest =cvCreateImage( cvSize(src->width,src->height), src->depth, src->nChannels );


    cvCanny(src,dest,t1,t2,size);
    invert(dest);

    my_image* result=new my_image(dest);

    cvReleaseImage(&src);
    cvReleaseImage(&dest);
return result;
}

void invert(IplImage * dest){
    if(dest==NULL){
        std::cout<<"vstupni obraz je nulovy!!!";
        return;
    }

 uchar * data      = (uchar *)dest->imageData;
    // invert the image
    for(int i=0;i<dest->height;i++) for(int j=0;j<dest->width;j++) for(int k=0;k<dest->nChannels;k++)
       data[i*dest->widthStep+j*dest->nChannels+k]=255-data[i*dest->widthStep+j*dest->nChannels+k];
return ;
}


void my_mouse_callback_write_pixel( int event, int x, int y, int flags, void* param ){
    IplImage* image = (IplImage*) param;

    switch( event ){
            case CV_EVENT_MOUSEMOVE:

                    break;

            case CV_EVENT_LBUTTONDOWN:
                    CvScalar s;
                    s=cvGet2D(image,y,x);
                    std::cout<<"bod "<<x<< "x" <<y<< " hodnota "<<s.val[0]<<std::endl;//<< <<std::endl;
                    //std::cout<<"bod"<<std::endl;
                    break;

            case CV_EVENT_LBUTTONUP:

                    break;
    }

}



