#include "cworktableoffset.h"
#include "logic_local_def.h"
CWorktableOffset::CWorktableOffset(const QString& name,int32_t id)
    :CChannel(name,id)
{

    m_Variants.add_Variant(Var_WorkTable_Offset_EnableOffset,
                           QObject::trUtf8("EnableOffset"),false,false,
                           Variant::TOXML);
    m_Variants.add_Variant(Var_WorkTable_Offset_Threshold,
                           QObject::trUtf8("Threshold"),double(0),false,
                           Variant::TOXML);
    m_offsetList.clear();
    m_offsetListCur.clear();
}

CWorktableOffset::~CWorktableOffset()
{

}
QDomElement CWorktableOffset::WriteConfig(QDomDocument &doc, QDomElement &root)
{
    writeOffsetList();
	writeOffsetToCsv();
    return CChannel::WriteConfig(doc,root);
}

int CWorktableOffset::ReadConfig(QDomElement &root)
{
    readOffsetList();

    return CChannel::ReadConfig( root);
}

void CWorktableOffset::writeOffsetList()
{
    QString strPath=
            CMakePath::make_config_path("Worktable_Offset.ldf");
    QFile file(strPath);
    if(!file.open(QIODevice::WriteOnly))
    {
        return;
        MQT_THROW_STR(QObject::trUtf8("open path %1 failed")
                      .arg(strPath));
    }
    QDataStream stream(&file);
    int iSize=m_offsetList.size();
    stream<<iSize;
    OFFSETLIST::iterator ii;
    for (ii=m_offsetList.begin();ii!=m_offsetList.end();ii++)
    {
        stream<<(*ii).first<<(*ii).second;
    }
}

void CWorktableOffset::readOffsetList()
{
    QString strPath=
            CMakePath::make_config_path("Worktable_Offset.ldf");
    QFile file(strPath);
    if(!file.open(QIODevice::ReadOnly))
    {
        return;
        MQT_THROW_STR(QObject::trUtf8("open path %1 failed")
                      .arg(strPath));
    }
    QDataStream stream(&file);
    m_offsetList.clear();
    int iSize;
    stream>>iSize;
    for (int j=0;j<iSize;j++)
    {
        QPair<double,double> pair;
        stream>>pair.first>>pair.second;
        m_offsetList.push_back(pair);
    }
}

void CWorktableOffset::writeOffsetToCsv()
{
	QString strPath=
		CMakePath::make_config_path("Worktable_Offset.csv");
	QFile file(strPath);
	if(!file.open(QIODevice::WriteOnly))
	{
		return;
		MQT_THROW_STR(QObject::trUtf8("open path %1 failed")
			.arg(strPath));
	}
	QTextStream stream(&file);
	int iSize=m_offsetList.size();
	stream<<"Pos,Offset\n";
	OFFSETLIST::iterator ii;
	for (ii=m_offsetList.begin();ii!=m_offsetList.end();ii++)
	{
		stream<<(*ii).first<<","<<(*ii).second<<"\n";
	}
}

void CWorktableOffset::Serialize(QDataStream &stream, bool bwrite)
{
    UNUSED(stream);
    UNUSED(bwrite);
}

