/***************************************************************************
                   Job Base Class  ( Job.cpp )
                -----------------------------------------

	begin      : 2013/03/21
	copyright  : (C) 2013 Solbox Inc.
	author     : Development 1 Team
					- 2013/03/21 - 1st dadamin
	email      : dev1@solbox.com
	version    : 3.2.0

	CopyRight(C) 2005 Solbox Inc. All Rights reserved.
	Redistribution and use in source and binary forms, with or with out
	modification, are not permitted in outside of Solbox Inc.
***************************************************************************/
#include "rc_mngd.h"
#include "Job.h"
#include "Logger.h"
#include "md5.h"

// job base class
CJob::CJob()
{

}

CJob::~CJob()
{

}

int	CJob::ExistUser( CRCDBControl &rcdb, CJobDataMap &jobData )
{
	bool exist = false;
	
	// check 
	if( !rcdb.CheckUserInfo(jobData, exist) )
	{
		return JOB_ERR_CHK_USER;
	}

	if(!exist)
		return 0;

	return 1;
}

int	CJob::ExistProduct(CRCDBControl &rcdb, CJobDataMap &jobData )
{
	bool exist = false;
	if(!rcdb.CheckProductInfo(jobData, exist) )
	{
		return JOB_ERR_CHK_PRODUCT;
	}

	if(!exist)
		return 0;

	return 1;
}

int	CJob::ExistInfo(CRCDBControl &rcdb, CJobDataMap &jobData )
{
	int r = 0;

	r = ExistUser(rcdb, jobData);
	if( r < 0 )
		return r;

	if( r == 0 )
		return JOB_ERR_USER_EMPTY;

	r = ExistProduct(rcdb, jobData);

	if( r < 0 )
		return r;

	if( r == 0 )
		return JOB_ERR_PRODUCT_EMPTY;
	
	r = 1;
	return r;
}

bool CJob::CheckIdentify( CJobDataMap &jobData )
{
	if( jobData[KEY_REQ_USER_PASS_CRYPTED].empty() )
	{
		LOG(LWAR, "Requested data to the user password is empty.");
		return true;
	}

	ostringstream passwdcrty;

	passwdcrty << jobData[KEY_SP_SVC_ID] << "@" << jobData[KEY_SP_USER_ID] 
	<< jobData[KEY_SP_USER_PASSWORD] << jobData[KEY_REQ_REG_DATE];

	MD5 *md5hasher = new MD5();

	char *pszHashed = NULL;
	md5hasher->update((unsigned char *)passwdcrty.str().c_str(), passwdcrty.str().size());
	md5hasher->finalize();
	pszHashed = md5hasher->hex_digest();

	bool r = true;
	if( jobData[KEY_REQ_USER_PASS_CRYPTED].compare(pszHashed) != 0)
	{
		r = false;
		LOG(LNOT, "Password not match.");		
	}

	if(md5hasher) delete md5hasher;
	if(pszHashed) delete [] pszHashed;

	return r;
}

bool CJob::IsSubKey (CJobDataMap &jobData, string key)
{
	if(jobData[KEY_JOBSUB_TYPE].compare(key) == 0)
		return true;
	return false;
}

bool CJob::FindInSubKey(CJobDataMap &jobData, string key)
{
	size_t found = jobData[KEY_JOBSUB_TYPE].find(key);
	if (found != string::npos)
		return true;

	return false;
}
