#include "logic.h"
#include "CBarcodeDriverInfoScan.h"
#include "cmserialport.h"
#include "cbarcode.h"
#define  MAX_COMMAND_LEN 32
CBarcodeDriverInfoScan::CBarcodeDriverInfoScan(const QString& name,int32_t id)
	: CBarCodeDriver(name, id)
{

}

CBarcodeDriverInfoScan::~CBarcodeDriverInfoScan(void)
{
}

void CBarcodeDriverInfoScan::GetBarCode(int iCHID)
{
	if(IsSimulator()) {
		CBarCode* pBarCodeSimulator = (CBarCode*)FindChannel(iCHID);
		pBarCodeSimulator->m_strBarCode = "Unidentified";
		return;
	}
	QMutexLocker locker(&m_CardMutex);
	char sendBuff[3] = {0x16, 0x54, 0x0D};
	m_pSerialPort->send(sendBuff,3);
	LogRecord(fmt::format("send:{}" , sendBuff));
	
	int irtn = m_pSerialPort->wait();

	char pResponse[MAX_COMMAND_LEN]={0};
	m_pSerialPort->receive(pResponse,irtn);

	LogRecord(fmt::format("receive:{}", pResponse));
	if(false == CheckResponse(pResponse))
	{
		LogRecord(fmt::format("format-error:{}", pResponse));
		MQT_THROW_STR(QObject::trUtf8("Send command response error. Driver:%1 Command:%2 Response:%3")
				.arg(m_sName).arg(sendBuff).arg(pResponse));
	}

	CBarCode* pBarCode=(CBarCode*)FindChannel(iCHID);


    if(strlen(pResponse)<=1){
        pBarCode->m_strBarCode = "Unidentified";
    }
    else{
        pBarCode->m_strBarCode = pResponse;
    }

	LogRecord(fmt::format("data:{}", pBarCode->m_strBarCode.toStdString()));
}

bool CBarcodeDriverInfoScan::CheckResponse(char *pResponse)
{
	int buffLen = strlen(pResponse);
	if(buffLen<3 && pResponse[buffLen-1] != 0x0A && pResponse[buffLen-2] != 0x0D){
		return false;
	}
	else
	{
		pResponse[buffLen-2] = 0;
		pResponse[buffLen-1] = 0;
		return true;
	}
}

int CBarcodeDriverInfoScan::ReadConfig(QDomElement &root)
{
	//HACK:解析配置文件流程
	//int iIndex=CWorkTable::ReadConfig(root);
	//QDomNodeList List =  root.childNodes();
	//Q_ASSERT(iIndex<List.size());
	/*CHCOORDMAP::iterator ii=mChCoords.begin();
	for(;ii!=mChCoords.end();ii++)
	{
		ii->ReadConfig( List.at(iIndex).toElement());
		iIndex++;
	}*/
	//m_pSerialPort->ReadConfig(root);

	return CBarCodeDriver::ReadConfig(root);	
}

int32_t CBarcodeDriverInfoScan::init_driver()
{
	if(!m_gSystem.IsSimulator()) {
		m_pSerialPort->open();
	}
	return RTN_SUCCESS1;
}

int32_t CBarcodeDriverInfoScan::exit_driver()
{
	m_pSerialPort->close();
	return RTN_SUCCESS1;
}
