#include "BoundingBox.h"
#include <cmath>


BoundingBox::BoundingBox()
{
}


BoundingBox::~BoundingBox()
{
}

// func: delivers bounding Boxes of contours
// pre: contours contains the contours for which bounding boxes have to be delivered
// post: bbs contains all bounding boxes. The index corresponds to the index of contours.
// I.e. bbs[i] belongs to contours[i]
int BoundingBox::allBoundingBoxes(const vector<vector<Point>> & contours, vector<vector<Point>> & bbs)
{
	for (vector<Point> contour : contours)
	{
		int maxx = INT_MIN, maxy = INT_MIN, minx = INT_MAX, miny = INT_MAX;

		for (Point p : contour)
		{
			if (p.x > maxx)
				maxx = p.x;

			if (p.y > maxy)
				maxy = p.y;
			
			if (p.x < minx)
				minx = p.x;

			if (p.y < miny)
				miny = p.y;
		}

		vector<Point> bounding;
		bounding.push_back(Point(minx, miny));
		bounding.push_back(Point(maxx, miny));
		bounding.push_back(Point(maxx, maxy));
		bounding.push_back(Point(minx, maxy));
		bbs.push_back(bounding);
	}

	return contours.size();
}

int BoundingBox::split(const vector<vector<Point>> & contours, const Mat &image, string filename)
{
	//Create filenames
	std::string base_filename = filename.substr(filename.find_last_of("/\\") + 1);
	std::string::size_type const p(base_filename.find_last_of('.'));
	std::string name = base_filename.substr(0, p);

	vector<vector<Point>> bounds;
	allBoundingBoxes(contours, bounds);

	//Find largest bounding box
	Size largest = Size(0,0);
	for (vector<Point> box : bounds)
	{
		int height = abs(box[2].y - box[1].y);
		int width = abs(box[1].x - box[0].x);

		if (height > largest.height)
			largest.height = height;
		if (width > largest.width)
			largest.width = width;
	}

	int nr = 0;

	//Create every image
	for (vector<Point> box : bounds)
	{
		Point center = Point((box[0].x + box[2].x) / 2, (box[0].y + box[2].y) / 2);
		
		Rect r = Rect(center.x - (largest.width / 2), center.y - (largest.height / 2),largest.width, largest.height);
		Mat roi(image, r);

		//imshow(name, roi);
		imwrite("output/" + name + "_" + to_string(nr) + ".bmp", roi);
		
		nr++;
	}

	return 1;
}