#include "opencv2/opencv.hpp"
#include <iostream>
#include "mpi.h"

using namespace std;
using namespace cv;

uchar **matToArray( cv::Mat array);
int diffVec(Vec3b & first, Vec3b & second);

int main(int argc, char* argv[])
{
    int procRank,procCount;
    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&procCount);
    MPI_Comm_rank(MPI_COMM_WORLD,&procRank);

    int childProcesses = procRank -1;

    // Create a VideoCapture object and open the input file
    // If the input is the web camera, pass 0 instead of the video file name
    VideoCapture cap("teapot.mp4");

    // Check if camera opened successfully
    if(!cap.isOpened()){
        cout << "Error opening video stream or file" << endl;
        return -1;
    }

    Mat oldFrame;
    while(1){

        Mat frame;
        // Capture frame-by-frame
        cap >> frame;

        // If the frame is empty, break immediately
        if (frame.empty())
            break;

        if (oldFrame.empty()) {
            oldFrame = frame;
            continue;
        }

        cv::Mat newMat = cv::Mat(frame.rows, frame.cols, frame.type()); // frame.clone();

        for(int i=0;i<frame.rows;i++){
            for(int j=0;j<frame.cols;j++){
                auto oldPxl = oldFrame.at<Vec3b>(i, j);
                auto currPxl = frame.at<Vec3b>(i, j);

                // Summiert die Vekotren nach der euklidischen Norm (Von OpenCV)
                int diff = norm(oldPxl - currPxl);


                if(diff > 20) {
                    Vec3b & color = newMat.at<Vec3b>(i,j);

                    // ... do something to the color ....
                    color[0] = 255;
                    color[1] = 255;
                    color[2] = 255;

                } else {
                    Vec3b & color = newMat.at<Vec3b>(i,j);

                    // ... do something to the color ....
                    color[0] = 0;
                    color[1] = 0;
                    color[2] = 0;
                }
            }
        }

        oldFrame = frame;

        imshow( "Live", frame );
        imshow( "MotionDetection", newMat );

        // Press  ESC on keyboard to exit
        char c=(char)waitKey(10);
        if(c==27)
            break;
    }


    cout << "Worked with " << procCount << " Prozesses!" << endl;


    // When everything done, release the video capture object
    cap.release();

    // Closes all the frames
    destroyAllWindows();
    MPI_Finalize();

    return 0;
}