#include "rcdu.h"
#include "Database.h"
#include "Logger.h"
#include "infomanager.h"

CInfoManager::CInfoManager() 
{
	
}

CInfoManager::~CInfoManager()
{

}

bool CInfoManager::loadInfo( DataBase &db, const char* servicid ) 
{
	ostringstream sql;
	sql << "SELECT sp_user_seq, sp_svc_tran_id, sp_svc_id, cal_used_depth FROM t_sms_sp_svc_product";
	
	if( servicid && strlen(servicid) )
		sql << " WHERE sp_svc_id = '" << servicid << "'";

#ifdef _DEBUG
	cout << "loainfo SQL : " << sql.str() << endl;
#endif // _DEBUG

	db.PgDoExec( const_cast<char*> (sql.str().c_str()) );

	if( db.PgResult(DataBase::NOT_CLEAR) < 0 )
	{
		LOG(LERR, "Cal depth load fail.");
		return false;
	}

	for( int i = 0; i < db.GetNoTuples(); ++i )
	{
#ifdef _DEBUG
		cout << "Load info - " << i << "," << db.GetValue(i,0) << "," << db.GetValue(i,1)
			<< "," << db.GetValue(i,2) << "," << db.GetValue(i,3) << endl;
#endif //_DEBUG
		CRCduInfo data;
		data.setInfoUserseq(atoll(db.GetValue(i,0)));
		data.setInfoTranid(atoll(db.GetValue(i,1)));
		data.setInfoService(db.GetValue(i,2));
		data.setInfoCaldepth(atoi(db.GetValue(i,3)));
		m_infolist.push_back(data);
	}
	db.PgClear();

	// row zero
	if(m_infolist.empty())
	{
		 LOG(LERR, "Empty Service ID.");
		 return false;
	}

	return true;
}

bool CInfoManager::changDepth( DataBase &db, int changdepth )
{
	RCUDINFOLIST::iterator i;

	for (i = m_infolist.begin(); i != m_infolist.end(); ++i )
	{
#ifdef _DEBUG
		cout << "change Depth - " << (*i).getInfoService() << "," << (*i).getInfoCaldepth() << endl;
#endif //_DEBUG
 		
		// check changed cal depth
		if( isChanged( (*i).getInfoCaldepth(), changdepth) )
		{
			ostringstream sql;
			sql << "UPDATE t_sms_sp_svc_product SET cal_used_depth = " 
				<< 	changdepth << " WHERE sp_svc_tran_id = "<< (*i).getInfoTranid();

			db.PgDoExec(const_cast<char *> (sql.str().c_str()));
			if( db.PgResult(DataBase::CLEAR) < 0) 
			{
				cerr << "[error] Update error.[cal_used_depth - " << (*i).getInfoService() << "]" << endl;
				LOG(LERR, "Update cal_used_depth failed.[service_id - %s]", (*i).getInfoService());
			}

			_LOG(LINF, "Changed depth - Service id: %s, depth : %d", (*i).getInfoService() , changdepth );
		}
		else 
		{
			_LOG(LNOT, "Skip %s - changed cal_used_depth.", (*i).getInfoService() );
		}
	}
	
	return true;
}
