#include "demowidget.h"
#include <QPaintEvent>
#include <QPainter>
#include <QPen>
#include <QBrush>
const int rows = 64;
const int cols = 64;
int
		startx = rand() % cols,
		starty = rand() % rows;
int
		endx = (startx + rand() % (cols-3) + 2) % cols,
		endy = (starty + rand() % (rows-3) + 2) % rows;

std::vector<int> cx,cy,idx,rx,ry,ridx;

demoWidget::demoWidget(QWidget *parent) : QWidget(parent)
{
	resize(640,640);
	for (int i=0;i<rows;++i)
	{
		std::vector<char> v(cols,1);
		v_mat.push_back(std::move(v));
	}
}

void demoWidget::paintEvent(QPaintEvent * evt)
{
	QPainter painter(this);
	QPen pen (Qt::NoPen);
	QBrush brush_valid(QColor(255,255,255));
	QBrush brush_block(QColor(0,0,0));
	QBrush brush_start(QColor(255,0,0));
	QBrush brush_raw(QColor(0,128,0));
	QBrush brush_end(QColor(0,0,255));
	QPen pen_line (brush_start,2);
	QPen pen_lineraw (brush_raw,3,Qt::DotLine);


	painter.setPen(pen);
	painter.setBrush(brush_valid);

	QSize sz = size();
	double dx = sz.width() * 1.0/(cols);
	double dy = sz.height()* 1.0/(rows);
	for (int i=0;i<rows;++i)
	{
		for (int j=0;j<cols;++j)
		{
			if (v_mat[i][j]==0)
				painter.setBrush(brush_block);
			else
				painter.setBrush(brush_valid);
			painter.drawRect(j * dx , i *dx,dx, dy);
		}
	}

	painter.setBrush(brush_start);
	painter.drawEllipse(startx * dx , starty *dx,dx, dy);
	painter.setBrush(brush_end);
	painter.drawEllipse(endx * dx , endy *dx,dx, dy);

	if (ridx.size())
	{
		const int impsz = ridx.size();

		painter.setPen(pen_lineraw);
		for (int i=0;i<impsz-1;++i)
		{
			const int curx1 = rx[ridx[i]] * dx+ dx/2;
			const int cury1 = ry[ridx[i]] * dy + dy/2;
			const int curx2 = rx[ridx[i+1]] * dx + dx/2;
			const int cury2 = ry[ridx[i+1]] * dy + dy/2;
			painter.drawLine(curx1,cury1,curx2,cury2);
		}
	}

	if (idx.size())
	{
		const int impsz = idx.size();

		painter.setPen(pen_line);
		for (int i=0;i<impsz-1;++i)
		{
			const int curx1 = cx[idx[i]] * dx+ dx/2;
			const int cury1 = cy[idx[i]] * dy + dy/2;
			const int curx2 = cx[idx[i+1]] * dx + dx/2;
			const int cury2 = cy[idx[i+1]] * dy + dy/2;
			painter.drawLine(curx1,cury1,curx2,cury2);
		}
	}

	QString it = QString("Iter = %1 times.").arg(iter);
	painter.drawText(1,16,it);


	evt->accept();
}

void demoWidget::mousePressEvent(QMouseEvent * evt)
{
	v_mat.clear();
	for (int i=0;i<rows;++i)
	{
		std::vector<char> v_row(cols,1);
		v_mat.push_back(std::move(v_row));
	}
	for (int i=0;i<128;++i)
	{
		v_mat[rand()%rows][rand()%cols] = 0;
	}

	startx = rand() % cols;
	starty = rand() % rows;

	endx = (startx + rand() % (cols-3) + 2) % cols;
	endy = (starty + rand() % (rows-3) + 2) % rows;

	v_mat[starty][startx] = 1;
	v_mat[endy][endx] = 1;


	//找路径,不归并
	min_distance_find(v_mat, startx,starty,  endx,endy,  &rx,&ry,&ridx,false);
	//找路径,做归并
	iter = min_distance_find(v_mat, startx,starty,  endx,endy,  &cx,&cy,&idx,true);
	update();

}
