#include "stdafx.h"
#include "safaricookiegetter.h"


#include "namespace_start.h"

browsertype::BrowserType CSafariCookieGetter::BT = browsertype::SAFARI;

CSafariCookieGetter::CSafariCookieGetter():
Base(CreateCookiePath())
{}

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

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


}

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

	MString mdomein;
	ToUTF8(mdomein,domein);
	MString mname;
	ToUTF8(mname,name);
	MString mval;
	ULong dataSizetmp;
	const Byte * startPointer = memmem(data,dataSize,mname.c_str(),mname.size());
	const Byte * domeinStartPointer;
	const Byte * cookieStartPointer;
	if(startPointer != nullptr){
		
		do{
			startPointer += mdomein.size();
			dataSizetmp =  dataSize - (startPointer - data);
			cookieStartPointer = memmem(startPointer,dataSizetmp,mname.c_str(),mname.size());
			domeinStartPointer = memmem(startPointer,dataSizetmp,mdomein.c_str(),mdomein.size());

			if(domeinStartPointer != nullptr && mdomein == reinterpret_cast<const Char*>(domeinStartPointer)){

				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,mname.c_str(),mname.size());
		}while(startPointer != nullptr);
		
	}

	return false;
}

NString CSafariCookieGetter::CreateCookiePath(){

	NString cookieFilePath;
	GetAppDataDirectry(cookieFilePath);
	cookieFilePath += _T("\\Apple Computer\\Safari\\Cookies\\Cookies.binarycookies");

	return cookieFilePath;

}


#include "namespace_end.h"