#include "stdafx.h"
#include "operacookiegetter.h"


#include "namespace_start.h"

browsertype::BrowserType COperaCookieGetter::BT = browsertype::OPERA;

COperaCookieGetter::COperaCookieGetter():
Base(CreateCookiePath())
{}

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

	return ForceSearch(cookieFilePath,domein,name,cookie,COperaCookieGetter::Fancta);


}

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

	MString mdomein;
	ToUTF8(mdomein,domein);
	std::regex reg(".jp");
	mdomein = std::regex_replace(mdomein,reg,MString(""));
	MString mname;
	ToUTF8(mname,name);
	MString mval;
	ULong dataSizetmp;
	const Byte * startPointer = memmem(data,dataSize,mdomein.c_str(),mdomein.size());
	const Byte * nameStartPointer;
	const Byte * cookieStartPointer;
	if(startPointer != nullptr){
		
		do{
			startPointer += mdomein.size();
			dataSizetmp =  dataSize - (startPointer - data);
			nameStartPointer = memmem(startPointer,dataSizetmp,mname.c_str(),mname.size());

			if(nameStartPointer != nullptr){
				cookieStartPointer = nameStartPointer +  mname.size() + 2;
				if(cookieStartPointer != nullptr){

					mval = reinterpret_cast<const Char*>(cookieStartPointer);

					std::regex reg2("([^a-z0-9_-])+");
					mval = std::regex_replace(mval,reg2,MString(""));
					U16String val;
					UTF8ToUTF16(val,mval);
					cookie.SetCookieValue(val);
					return !val.empty();

				}

			}

			startPointer = memmem(startPointer,dataSizetmp,mdomein.c_str(),mdomein.size());
		}while(startPointer != nullptr);
		
	}

	return false;
}

NString COperaCookieGetter::CreateCookiePath(){

	NString cookieFilePath;
	GetAppDataDirectry(cookieFilePath);
	cookieFilePath += _T("\\Opera\\Opera\\cookies4.dat");

	return cookieFilePath;

}


#include "namespace_end.h"