#include "SensorMannager.h"
#include "SensorQExPRO.h"
#include <QThread>
#include "logout.h"
#include "QDateTime"
#include "QLocale"
#include"SensorOptoSky.h"
int maxtime = 30000;
SensorMannager::SensorMannager(QObject *parent )
	: QObject(parent)
{

	Numberofscan = 5;
	//Sensor = new SensorQExPRO(QEPRO_QE); 
	Sensor = new SensorOptoSky(ATP6500,"COM12");
	Sensor->initSensor();
}

SensorMannager::~SensorMannager()
{
	delete Sensor;
	logout::out("退出",1);

}

void SensorMannager::opensensor()
{
	Sensor->initSensor();
}

void SensorMannager::CloseSensor()
{
	Sensor->CloseSensor();
}

long SensorMannager::SensorOpt(int persent)
{
	long maxvalue = Sensor->SensorInfo.maxValue*1.0*persent / 100;
	STROnePlot plot;
	long maxvaluenow = 0;
	float shutternow = 10;
	if (Sensor->SensorType=="USB2000PLUS")
	{
	//	shutternow = 1;
	}
	
	Sensor->Settingshuttertime(shutternow);
	
	Sensor->GetOnePlot(plot);
	if (!plot.isInit)
	{
		return -1;
	}
	maxvaluenow = Getmaxvalue(plot.Plot,4, plot.BandNum-4);
	logout::out("自动曝光为: " + QString::number(shutternow) + " 毫秒   最大值为" + QString::number(maxvaluenow),1);
	//QThread::msleep(1000);
	int numberoftry = 0;
	while (maxvaluenow<maxvalue*0.95 ||maxvaluenow>maxvalue)
	{

			if (maxvaluenow > maxvalue)
			{
				shutternow = shutternow *0.9;
			}
			else
			{
				shutternow = maxvalue * 0.98 / (maxvaluenow * 1.0)*shutternow + 1;
			}
			if (shutternow>maxtime)
			{
				shutternow = maxtime;
			}
			//QThread::msleep(100);
			Sensor->Settingshuttertime(shutternow);
			Sensor->GetOnePlot(plot);
			if (plot.isInit)
			{
				maxvaluenow = Getmaxvalue(plot.Plot, 4, plot.BandNum - 4);
				
			}

			
			numberoftry++;

			logout::out("自动曝光为: " + QString::number(shutternow) + " 毫秒   最大值为"+QString::number(maxvaluenow),1);
			if (numberoftry>200)
			{
				logout::out("曝光尝试次数过多 曝光失败",3);
				return -1;

			}
			if (shutternow == maxtime)
			{
				logout::out("曝光时间达到最大允许时间",3);
				return -1*maxtime;
			}

	}
	logout::out("曝光成功 曝光时间为: "+QString::number(shutternow)+" 毫秒",1);
	return shutternow;

}

long SensorMannager::Getmaxvalue(float *arr, int start, int lenth)
{
	long val = -1;
	for (size_t i = start; i < lenth; i++)
	{
		if (val <= arr[i])
		{
			val = arr[i];
		}

	}
	return val;
}

void SensorMannager::SetnumbertoGot(int nscan)
{
	Numberofscan = nscan;
}

void SensorMannager::GetSifData(QString outfilepath, bool isskyfirs /*= true*/)
{
	
	Sensor->SettingShutterOpen(true);//确保shutter打开
	QThread::msleep(50);
	Sensor->SettingSwitchShutter(true);//切换为sky
	logout::out("Switch 切换至SKY",1);
	QThread::msleep(50);
	//////////////////////////优化定标////////////////////////////////////////////////
	float skyshutter=SensorOpt();
	for (size_t i = 0; i < 3; i++)
	{

		if (skyshutter!=-1)
		{
			break;
		}
		skyshutter = SensorOpt();

	}
	/////////////////////////////////////////////
	if (skyshutter==-1)//opt三次后仍未-1 说明错误
	{
		logout::out("错误 结束程序",3);
		return;
	}
	skyshutter = abs(skyshutter);
	Sensor->SettingSwitchShutter(false);//切换为VEG
	logout::out("Switch 切换至VEG",1);
	QThread::msleep(50);
	//////////////////////////veg////////////////////////////////////////////////
	float vegshutter = SensorOpt();
	for (size_t i = 0; i < 3; i++)
	{
		if (vegshutter ==-1 )
		{
			break;
		}
		vegshutter = SensorOpt();

	}
	if (vegshutter == -1)
	{
		logout::out("错误 结束程序",3);
		return;
	}
	vegshutter = abs(vegshutter);
	//////////////////////////模块分割////////////////////////////////////////////////

	//////////////////////////打开带输出文件////////////////////////////////////////////////
	FILE *fp = fopen(outfilepath.toStdString().c_str(), "w");
	if (fp==NULL)
	{
		logout::out("打开文件" + outfilepath + "失败！！", 3);
		return;
	}
	//fprintf(fp, "%s）
	STROnePlot oneplot;
	float tempp = Sensor->GettingTempratrue();
	WriteTitletoCSV(fp, Sensor->SensorInfo.SensorName,Numberofscan, tempp, Sensor->SensorInfo.WavelenthStr, skyshutter, vegshutter);
	logout::setoutlevel(10);
	Sensor->SettingSwitchShutter(true);//切换至sky
	Sensor->Settingshuttertime(skyshutter);
	for (size_t i = 0; i < Numberofscan; i++)
	{
		logout::out("开始采集第"+QString::number(i+1)+"次Sky 数据");
		Sensor->GetOnePlot(oneplot,true);
		writeonedatatoCSV(fp, oneplot);
	}

	Sensor->SettingSwitchShutter(false);//切换为VEG
	Sensor->Settingshuttertime(vegshutter);
	for (size_t i = 0; i < Numberofscan; i++)
	{
		logout::out("开始采集第" + QString::number(i+1) + "次Veg 数据");
		Sensor->GetOnePlot(oneplot,true);
		writeonedatatoCSV(fp, oneplot);
	}
	fflush(fp);
	fclose(fp);
	logout::out("采集完成",1);
	logout::setoutlevel();

}

void SensorMannager::writeonedatatoCSV(FILE *fp, STROnePlot plot)
{
	//.fprintf(fp, "%s,%s,%s\n", xvaluetoWrite.at(i).toStdString().c_str()
	size_t lenth = plot.BandNum;
	size_t i;
	for (i = 0; i < lenth-1; i++)
	{
		fprintf(fp, "%s,", QString::number(plot.Plot[i], 'f', 1).toStdString().c_str());

	}
	fprintf(fp, "%s\n", QString::number(plot.Plot[i], 'f', 1).toStdString().c_str());
}

void SensorMannager::WriteTitletoCSV(FILE *fp, QString sensname, int NmberofScan, float temp, QString wavestring, float skyshutter, float vegshutter)
{
	if (fp == NULL)
	{
		return;
	}
	QDateTime datetime = QDateTime::currentDateTime();
	QLocale locale = QLocale::English;
	QString datestr = locale.toString(datetime, "ddd MMM dd hh:mm:ss yyyy");
	fprintf(fp, "observation date and time: %s\n", datestr.toStdString().c_str());
	fprintf(fp, "numberofscan: %s\n", QString::number(Numberofscan).toStdString().c_str());
	fprintf(fp, "spectrometer: %s\n", sensname.toStdString().c_str());
	fprintf(fp, "ambient temperature: %s\n", QString::number(temp,'f',2).toStdString().c_str());
	fprintf(fp, "%s\n", wavestring.toStdString().c_str());
	fprintf(fp, "integration time 1: %s\n", QString::number(skyshutter, 'f', 2).toStdString().c_str());
	fprintf(fp, "integration time 2: %s\n", QString::number(vegshutter, 'f', 2).toStdString().c_str());
}

