#include "stdafx.h"
#include "firefoxcookiegetter.h"



#include "namespace_start.h"

browsertype::BrowserType CFireFoxCookieGetter::BT = browsertype::FIREFOX;

CFireFoxCookieGetter::CFireFoxCookieGetter():
SQLiteCookieGetterT<CFireFoxCookieGetter>(_T("SELECT  a.value FROM moz_cookies a WHERE a.name = '%1%' AND a.baseDomain = '%2%' "),CreateCookiePath())
{

}

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

	Bool result = false;
	

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

	if(result == false){

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

	}

	return result;
}



NString CFireFoxCookieGetter::CreateCookiePath(){

	NString appdataPath;
	NString iniDir(_T("\\Mozilla\\Firefox\\"));
	NString cookieFileName(_T("cookies.sqlite"));
	NString val;
	if(GetAppDataDirectry(appdataPath)){

		NString iniPath = appdataPath + iniDir + _T("profiles.ini");
		NString cookiePathtmp;
		ReadIni(iniPath,_T("Profile0"),_T("Path"),cookiePathtmp);

		nregex reg(_T("/"));
		cookiePathtmp = std::regex_replace(cookiePathtmp,reg,NString(_T("\\")));
		NString val2;
		ReadIni(iniPath,_T("Profile0"),_T("IsRelative"),val2);
		Int patern = boost::lexical_cast<Int>(val2);

		switch(patern){

		case 0:
			val = cookiePathtmp + cookieFileName;
			break;


		case 1:
			val = appdataPath + iniDir + cookiePathtmp + _T("\\") +  cookieFileName;
			break;
		};
	}

	return val;
}
Bool CFireFoxCookieGetter::Fancta(const Byte * data,ULong dataSize,const NString & domein,const NString &name,CCookie &cookie){

	
	MString mdomein;
	MString startdomeinname;

	ToUTF8(mdomein,_T(".") + domein);
	ToUTF8(startdomeinname,domein+name);

	const Char * startPointer = reinterpret_cast<const Char*>(memmem(data,dataSize,startdomeinname.c_str(),startdomeinname.size()));
	
	if(startPointer != nullptr){
		startPointer += startdomeinname.size();
		U16String cookieValue;
		UTF8ToUTF16(cookieValue,startPointer,strstr(startPointer,mdomein.c_str()) - startPointer);
		cookie.SetCookieValue(cookieValue);
		return true;
	}


	return false;
}


#include "namespace_end.h"