#include "pch.h"
#include "Logger.h"
#include "Source/Settings/SysConfigger.h"
#include "BD357Ctrl.h"
#include "MainGrabber.h"
#include "ZZ_Types.h"
#include "DataFileProcessor.h"
#include "MakeDarkCurrentTable.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

bool is_mounted(const std::string& device, const std::string& mount_point)
{
	std::ifstream mounts("/proc/mounts");
	std::string line;

	if (mounts.is_open()) 
	{
		while (getline(mounts, line))
		{
			std::istringstream iss(line);
			std::string dev, mnt, fstype, options;

			if (iss >> dev >> mnt >> fstype >> options) 
			{
				if (dev == device && mnt == mount_point) 
				{
					mounts.close();
					return true;
				}
			}
		}
		mounts.close();
	}

	return false;
}

int main(int argc, char* argv[])
{
	using namespace ZZ_MISCDEF::ZZ_RUNPARAMS;
	using namespace ZZ_MISCDEF::MISC_DETECTOR;

	QCoreApplication a(argc, argv);

	//ָʾ�ƿ���
	//system("sudo mount / dev / mmcblk1p1 / home / data");
	system("gpio mode 4 out");
	system("gpio mode 5 out");

	qDebug() << "system(gpio mode 4 out)";
	qDebug() << "system(gpio mode 5 out)";

	///check tf card
	//���sd���Ƿ���أ����û�еƾͽ�����˸
	std::string device = "/dev/mmcblk1p1"; 
	std::string mount_point = "/home/data";
	if (!is_mounted(device, mount_point)/*1*/)
	{
		while (1)
		{
			system("gpio write 4 1");
			QEventLoop qeLoop;
			QTimer::singleShot(200, &qeLoop, SLOT(quit()));
			qeLoop.exec();
			system("gpio write 4 0");
			system("gpio write 5 1");

			QTimer::singleShot(200, &qeLoop, SLOT(quit()));
			qeLoop.exec();
			system("gpio write 5 0");
		}
	}

	// 拷贝说明书到 SD 卡
	if (!QFile::exists("/home/data/机顶辐照度使用说明书.md")) {
		if (QFile::exists("/root/机顶辐照度使用说明书.md")) {
			QFile::copy("/root/机顶辐照度使用说明书.md", "/home/data/机顶辐照度使用说明书.md");
		}
	}

	//////////////////////////////////////////////////////////////////////////Check configdatairis folder
	QDir qdirConfigDataIris("/home/data/configdatairis");
	if (qdirConfigDataIris.exists())
	{
		printf("configdatairis folder found. Copying config files...\n");

		QFileInfo fiSettings("/home/data/configdatairis/DeviceSettings.ini");
		if (fiSettings.isFile() && fiSettings.size() >= 50)
		{
			QFile::copy("/home/data/configdatairis/DeviceSettings.ini", "/root/DeviceSettings.ini");
			printf("  DeviceSettings.ini copied.\n");
		}

		QFileInfo fiDCTable("/home/data/configdatairis/DCTable.txt");
		if (fiDCTable.isFile())
		{
			QFile::copy("/home/data/configdatairis/DCTable.txt", "/root/DCTable.txt");
			printf("  DCTable.txt copied.\n");
		}

		// 删除configdatairis文件夹
		qdirConfigDataIris.removeRecursively();
		printf("configdatairis folder removed.\n");
	}
	//////////////////////////////////////////////////////////////////////////Check configdatairis folder



	if (!QFile::exists("/home/data/stopwait.txt")) {
		QEventLoop qeLoop;
		 QTimer::singleShot(30000, &qeLoop, SLOT(quit()));
		// //QTimer::singleShot(10000, &qeLoop, SLOT(quit()));
		 qeLoop.exec();
	}
	// QTimer::singleShot(30000, &qeLoop, SLOT(quit()));
	// //QTimer::singleShot(10000, &qeLoop, SLOT(quit()));
	// qeLoop.exec();

	

	OneFSContext m_struFSParam;//������
	GPSInfo      m_struGPSInfo;
	//FodisRP      m_struMiscRunParams;
		 
	ZZ_SysConfigger       m_syscfSettings;//������
	BD357Controller       m_ctrlGPS;
	CMainGrabber          m_mgMainGrabber;//���ɼ�
	DataFileProcessor     m_dfpDataSaver;

#ifndef WIN32
	QT_LOG::ZZ_InitLogger("/home/data/Log/"); //test
#endif

	//////////////////////////////////////////////////////////////////////////test code block 
	//DataFrame aaaa;
	//int xxxx = sizeof(aaaa);
	//m_dfpDataSaver.LoadWaveLengthFile("E:/WavelengthInfo.txt");
	//m_dfpDataSaver.LoadSingleDataFile("D:/Data/2023_07_04/15_55_18.dat");
	//m_dfpDataSaver.RecoverBackground("D:/Data/2023_07_04/15_55_18.dat", "D:/DCTable.txt");
	//////////////////////////////////////////////////////////////////////////test code block
	//////////////////////////////////////////////////////////////////////////Check Settings File
	bool bRes = false;

	QFileInfo m_qfiSettingFileInfo("/home/data/Setting/DeviceSettings.ini");

	// 如果SD卡上有配置文件，拷贝到/root下
	if (m_qfiSettingFileInfo.isFile() && m_qfiSettingFileInfo.size() >= 50)
	{
		printf("DeviceSettings found on SD card. Copying to /root...");
		QFile::copy("/home/data/Setting/DeviceSettings.ini", "/root/DeviceSettings.ini");
		printf("Done.\n");
	}
	//////////////////////////////////////////////////////////////////////////Check Settings File
	//////////////////////////////////////////////////////////////////////////Load Settings File
	///configger
	m_syscfSettings.Initialize();
	bRes = m_syscfSettings.LoadSettings_FS(m_struFSParam);
	if (!bRes)
	{
		//qDebug() << "LoadSettings_FS Err." << endl;
		printf("LoadSettings_FS Err.");
		return 1;
	}
	bRes = m_syscfSettings.LoadSettings_GPS(m_struGPSInfo);
	if (!bRes)
	{
		//qDebug() << "LoadSettings_GPS Err." << endl;
		printf("LoadSettings_GPS Err.");
		return 1;
	}
	/////
    //////////////////////////////////////////////////////////////////////////Check DCTable 
	using namespace ZZ_MISCDEF;
	if (m_struFSParam.ucDeviceModel== DeviceModel::FLAME)
	{
		//do nothing
	}
	else
	{
		QFileInfo m_qfiDCTFileInfo("/home/data/Data/DCTable.txt");
		if (!m_qfiDCTFileInfo.isFile())
		{
			printf("DCTable File Missing !!! Will create from default one.");

			QDir qdirPath("/home/data/Data");
			if (!qdirPath.exists())
			{
				bool bRes = qdirPath.mkpath("/home/data/Data");
				if (!bRes)
				{
					qDebug() << "DataFileProcessor mkdir Failed.";
					return -1;
				}
			}
			bool bRes = QFile::copy("/root/DCTable.txt", "/home/data/Data/DCTable.txt");
			if (!bRes)
			{
				qDebug() << " QFile::copy Failed.";
				return -2;
			}
		}
	}
    //////////////////////////////////////////////////////////////////////////Check DCTable 
    ////////////////////////////////test only
    //MakeDCT m_test;
    //m_test.SetRunParams(m_struFSParam);
    //m_test.Initialize();
    //m_test.MakeTable();
    //m_test.Initialize_Part();
    //m_test.LoadTable();
	////////////////////////////////test only
	m_ctrlGPS.SetContext(m_mgMainGrabber);//��ʼ��gps
	m_ctrlGPS.SetupMessagePipeline();
	m_ctrlGPS.Initialize(m_struGPSInfo);

	QThread* m_pqDataGrabberThreadHolder = new QThread();
	m_mgMainGrabber.moveToThread(m_pqDataGrabberThreadHolder);

	m_mgMainGrabber.SetRunParams(m_struFSParam);//��ʼ�����ɼ��߳�
	m_mgMainGrabber.SetContext(m_ctrlGPS, m_dfpDataSaver);

	m_pqDataGrabberThreadHolder->start();

	m_mgMainGrabber.Initialize();//��ʼ����

	//m_ctrlGPS.VSlot_SkipSyncDateOnce();

	cout << "System Started..." << endl;
	///////

	//long long int a1;// 8
	//long long b;     // 8
	//double c;        // 8
	//qDebug()<<sizeof(a1)<< sizeof(b)<<sizeof(c);
	/////

	return a.exec();
}