#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");
		}
	}


	QEventLoop qeLoop;
	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");

	if (!m_qfiSettingFileInfo.isFile())
	{
		printf ("DeviceSettings File Missing !!! Will create from default one.");

		QDir qdirPath("/home/data/Setting");
		if (!qdirPath.exists())
		{
			bool bRes = qdirPath.mkpath("/home/data/Setting");
			if (!bRes)
			{
				qDebug() << "DataFileProcessor mkdir Failed.";
				return -1;
			}
		}

		bool bRes = QFile::copy("/root/DeviceSettings.ini", "/home/data/Setting/DeviceSettings.ini");
		if (!bRes)
		{
			qDebug() << " QFile::copy Failed.";
			return -2;
		}
	}
	else
	{
		int iSize = m_qfiSettingFileInfo.size();
		if (iSize<50)
		{
			bool bRes = QFile::remove("/home/data/Setting/DeviceSettings.ini");
			if (!bRes)
			{
				qDebug() << " QFile::remove Failed.";
				return -2;
			}

			bRes = QFile::copy("/root/DeviceSettings.ini", "/home/data/Setting/DeviceSettings.ini");
			if (!bRes)
			{
				qDebug() << " QFile::copy Failed.";
				return -2;
			}
		}
	}
	//////////////////////////////////////////////////////////////////////////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();
}