#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

#include "Training.h"
#include "Camera.h"
#include "FeatureExtractor.h"

using namespace std;
using namespace cv;

int run();

int main(int argc, char** argv)
{
	Camera cam(1);
	Training tr;
	
	cout << "Welcome to Jarvis" << endl;
	cout << "Would you like to calibrate the camera (c), take pictures (p), train the network (t) or run the neural network (r)?" << endl;

	char c;
	cin >> c;

	switch (c) {
	case 'c':
		cam.Calibrate();
		break;
	case 'p':
		tr.CreateTrainingSet();
		break;
	case 't':
		tr.LoadTrainingSet();
		break;
	case 'r':
		run();
		break;
	default:
		return 0;
	}

	cout << "The program has finished, press enter to exit" << endl;
	cin.ignore();

	return 0;
}

int run()
{
	Camera cam = Camera(1);
	NeuralNetwork bpn;
	bpn.Read();

	while (true)
	{
		//Take picture and pre-process
		Mat image, gray_image, binaryImage;

		image = cam.takeImage();
		cvtColor(image, gray_image, CV_BGR2GRAY);

		//Find contour
		vector<Point> contour;
		FeatureExtractor::findContour(gray_image, contour);

		//Extrax features
		FeatureExtractor ext = FeatureExtractor(contour);
		Mat descriptors = Mat_<double>();

		ext.Extract(descriptors);

		descriptors = transpose(descriptors);

		string cls;
		bpn.Predict(descriptors, cls);

		cout << "It\'s a " << cls << endl;

		// teken de contouren
		Point2f vertices2f[4];
		ext.Rectangle().points(vertices2f);

		// Convert them so we can use them in a fillConvexPoly
		Point vertices[4];
		for (int i = 0; i < 4; ++i) {
			vertices[i] = vertices2f[i];
		}

		// Now we can fill the rotated rectangle with our specified color
		fillConvexPoly(image, vertices, 4, Scalar(0, 0, 255));

		vector<vector<Point>> contours;
		contours.push_back(contour);
		drawContours(image, contours, -1, CV_RGB(0, 255, 0), 4);
		putText(image, cls, cvPoint(15, 30),
			FONT_HERSHEY_COMPLEX, 1.0, cvScalar(0, 0, 0), 1, CV_AA);

		imshow("Neural detection", image);

		waitKey(0);

		destroyAllWindows();
	}
}


/*
// Creeer een witte image
IplImage* iplimage = cvCreateImage(cvSize(binaryImage.cols, binaryImage.rows), IPL_DEPTH_8U, 3);
Mat contourImage = cvarrToMat(iplimage);
contourImage = Scalar(255, 255, 255);

// teken de contouren op de witte image
vector<vector<Point>> contours;
contours.push_back(contour);

Point2f vertices2f[4];
ext.Rectangle().points(vertices2f);

// Convert them so we can use them in a fillConvexPoly
Point vertices[4];
for (int i = 0; i < 4; ++i) {
	vertices[i] = vertices2f[i];
}

// Now we can fill the rotated rectangle with our specified color
fillConvexPoly(contourImage, vertices, 4, Scalar(0, 255, 0));
drawContours(contourImage, contours, -1, CV_RGB(255, 0, 0));

imshow("Features", contourImage);
waitKey(0);
*/