#include "stdafx.h"
#include "chromecookiegetter.h"


#include "namespace_start.h"


browsertype::BrowserType CChromeCookieGetter::BT = browsertype::CHROME;


CChromeCookieGetter::CChromeCookieGetter():
SQLiteCookieGetterT<CChromeCookieGetter>(_T("SELECT a.value FROM cookies a WHERE a.name = '%1%' AND a.host_key like '%2%'"),CreateCookiePath())
{

}

Bool CChromeCookieGetter::GetCookieInternal(const NString &domein,const NString &name,CCookie &cookie){

	Bool result = false;
	

	NString sql((nformat(SQL.c_str()) % name % (_T("%") + domein)).str()); 
	
	result = GetCookieSQLSingleFile(cookieFilePath,sql,cookie);

	if(result == false){

		ForceSearch(cookieFilePath,domein,name,cookie,Fancta);

	}

	return result;
}


NString CChromeCookieGetter::CreateCookiePath(){
	

	NString cookiePath;

	GetAppLocalDataDirectry(cookiePath);

	if(!cookiePath.empty()){
		cookiePath += _T("\\Google\\Chrome\\User Data\\Default\\Cookies");
	}

	return cookiePath;

	

}

Bool CChromeCookieGetter::Fancta(const Byte * data,ULong dataSize,const NString & domein,const NString &name,CCookie &cookie){

	MString searchString;
	ToUTF8(searchString,domein+name);
	const Char *startPointer = reinterpret_cast<const Char*>(memmem(data,dataSize,searchString.c_str(),searchString.size()) ) ;

	if(startPointer != nullptr){
		startPointer += searchString.size();
		U16String cookieValue;
		UTF8ToUTF16(cookieValue,startPointer,strstr(startPointer,"/") - startPointer);
		if(!cookieValue.empty() ){

			cookie.SetCookieValue(cookieValue);
			return true;

		}
	}
	return false;
}

#include "namespace_end.h"