#include<iostream>
#include <unistd.h>
#include "gstCapture.h"
#include <opencv2/videoio/videoio.hpp>
#include "opencv2/opencv.hpp"

using namespace std;


//std::string m_strMoviePath = "rtsp://root:mcp4ever@10.127.117.242:554/axis-media/media.amp";
std::string m_strMoviePath = "rtsp://localhost:8554/test";
std::string m_gStreamerPipeline = "rtspsrc location=" + m_strMoviePath + " ! decodebin !  videoconvert ! appsink name=mysink max-buffers=1 drop=true max-lateness=33000000 sync=false";
//std::string m_gStreamerPipeline = "rtspsrc location=###LOCATION### ! rtph264depay  !  h264parse  ! openh264dec ! appsink name=mysink max-buffers=1 drop=true max-lateness=33000000 sync=false";


bool initStream(int t)
{
	bool success = false;

	std::cout << "initializing stream: '" + m_strMoviePath + "'" << endl;	
	std::cout << "Connecting to input ..."<< endl;
	gstCapture m_camera;

		std::cout  << "Pipeline: " << m_gStreamerPipeline << endl;
		double fps = 0.0;
	
		std::cout << "Open stream" << endl;

		if (m_camera.openCapture(m_gStreamerPipeline))
			std::cout << "stream opened!" << endl;
		else
		{
			std::cout <<"failed to connect, returning"<< endl;
			m_camera.close();
			return false;
		}

	int i=0;
	bool frameRead = true;
	while (frameRead == true ) {

		if(i==100)
			break;
		cv::Mat frame;
		frameRead = m_camera.read(frame);

		if(frameRead) {
			auto duration = std::chrono::system_clock::now().time_since_epoch();
			auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();

			std::cout << "Frame #" << i << " read at timestamp [" << millis << "]" << endl;

			size_t numBytes= frame.total() * frame.channels();

			i++;
			frame.release();
		}
	}
	std::cout << "Finished reading " << i <<" frames for " << t << "th time."<< endl;
	m_camera.close();
	if(i==100)
		return true;
	return false;
}

int main() {

    std::cout << " GStreamer test program"<< endl;

    // run 100 times
    for(int t=1; t<=100; t++) { 
        initStream(t);
		std::cout << "Sleeping for 10 secs...\n\n";
    	sleep(10);
   }
	gst_deinit();
}
