#include "mainwindow.h"
#include <windows.h>
#include <thread>
#include <QPixmap>
#include <QMessageBox>
mainwindow::mainwindow(QWidget *parent) : QMainWindow(parent), isDisplay_(true)
{
    ui_.setupUi(this);
	//相机连接
	int status = connect();
	if (status != CAMERA_STATUS_SUCCESS)
	{
		QMessageBox::question(this, "error", QString("connect error, ret = ") + QString::number(status), "yes");
	}
	else
	{
		//预览图显示
		std::thread([this]
			{
				//设置为预览采集模式
				VSensorAPI_.SetCaptureMode(MODE_VIEW);
				//获取相机输出分辨率
				VSensorImageResolution ImageResolution;
				VSensorAPI_.GetImageResolution(&ImageResolution);
				unsigned char* pbyBufferprocessGray = new unsigned char[ImageResolution.Height * ImageResolution.Width * 2];
				unsigned char* pbyBufferprocessLeft = new unsigned char[ImageResolution.Height * ImageResolution.Width];
				unsigned char* pbyBufferprocessRight = new unsigned char[ImageResolution.Height * ImageResolution.Width];
				while (isDisplay_)
				{
					//获取相机输出预览图
					int status = VSensorAPI_.CameraOut(pbyBufferprocessGray, nullptr);
					if (status != CAMERA_STATUS_SUCCESS)
					{
						Sleep(10);
						continue;
					}
					else
					{
						//分割图像
						for (int j = 0; j < ImageResolution.Height; j++)
						{
							memcpy(pbyBufferprocessLeft + j * ImageResolution.Width, pbyBufferprocessGray + j * ImageResolution.Width * 2, sizeof(unsigned char) * ImageResolution.Width);
							memcpy(pbyBufferprocessRight + j * ImageResolution.Width, pbyBufferprocessGray + j * ImageResolution.Width * 2 + ImageResolution.Width, sizeof(unsigned char) * ImageResolution.Width);
						}
						setCaptureDisplay(QPixmap::fromImage(QImage(pbyBufferprocessLeft, ImageResolution.Width, ImageResolution.Height, QImage::Format_Indexed8)), QPixmap::fromImage(QImage(pbyBufferprocessRight, ImageResolution.Width, ImageResolution.Height, QImage::Format_Indexed8)));
					}
				}
				delete[] pbyBufferprocessGray;
				delete[] pbyBufferprocessLeft;
				delete[] pbyBufferprocessRight;
			}).detach();
	}
}
mainwindow::~mainwindow()
{
	isDisplay_ = false;
	Sleep(500);
	VSensorAPI_.DeviceUnInit();
}
int mainwindow::connect()
{
    VSensorCameraInfo cameraList[20];
    int num = 0;
    VSensorAPI_.GetDeviceList(cameraList, &num);
    int status = VSensorAPI_.DeviceConnect(0);
    if (status != CAMERA_STATUS_SUCCESS)
    {
		return status;
    }
    status = VSensorAPI_.DeviceParameterInit();
    if (status != CAMERA_STATUS_SUCCESS)
    {
		return status;
    }
	return CAMERA_STATUS_SUCCESS;
}
void mainwindow::setCaptureDisplay(QPixmap mapl, QPixmap mapr)
{
	QMetaObject::invokeMethod(this, [this, mapl, mapr]
		{
			ui_.label_left->setPixmap(mapl.scaled(ui_.label_left->width(), ui_.label_left->height(), Qt::IgnoreAspectRatio));
			ui_.label_right->setPixmap(mapr.scaled(ui_.label_right->width(), ui_.label_right->height(), Qt::IgnoreAspectRatio));
		});
}