#pragma once

#include <nlite_common\function.h>
#include "filecookiegetter.h"
#include "copycookiefilemanager.h"
#include <boost/utility.hpp>
#include <sqlite3\sqlitemanage.h>


#include "namespace_start.h"




template<typename T>
class SQLiteCookieGetterT:public CFileCookieGetterT<T>{

public:
	typename typedef CCookieGetterT<T> Base;


	SQLiteCookieGetterT(const NString &SQL,const NString &cookiePath):
	  SQL(SQL),
		  CFileCookieGetterT<T>(cookiePath)
	  {}

protected:
	const NString SQL;

	


public:

	Bool GetCookieSQLSingleFile(const NString &path,const NString &sql,CCookie &cookie){

		
		
	
		CCookieGetResult cookieResult = GetCookieSQLite(path,sql,cookie);

		if(! cookieResult.IsFound()){
			resultList.push_back(cookieResult);
			
			CCopyCookieFile copyFile(path);
			CCookieGetResult cookieResult2 = GetCookieSQLite(copyFile.GetFilePath(),sql,cookie);
			
			if(!cookieResult2.IsFound()){

				resultList.push_back(cookieResult);

			} else {

				return true;
			}

		} else {

			return true;
		}

		
		

		return false;
	}

	CCookieGetResult GetCookieSQLite(const NString &path,const NString &sql,CCookie &cookie){

		
		
	
		if(! PathIsFile(path)){
			THROW_EXCEPTION(Exception,_T("指定されたパスにクッキーファイルが存在しません"));
			

		}
		
		sqlite::CDB db;
		
		CCookieGetResult result(BT);
		
		Int rcopen = db.Open(path,SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE);
		
		if(rcopen != SQLITE_OK){

			result.SetResultCode(resultcode::ERR_SQLITE);
			result.SetSQLiteResult(rcopen);
			
			
		} else {

		
			sqlite::CStatement stmt;
			Int rcprepare = db.Prepare(sql,stmt);
			
			if(rcprepare == SQLITE_OK){

				Int rcstep = stmt.Step();

				if( rcstep == SQLITE_ROW){
				
					const CharU16* cookieValue = stmt.Column(0);

					if(cookieValue != nullptr){
						

						cookie.SetCookieValue(cookieValue);

						result.SetFindFlag(true);
					}
				} else {

					result.SetResultCode(resultcode::ERR_SQLITE);
					result.SetSQLiteResult(rcstep);
				}
				


			} else {

				result.SetResultCode(resultcode::ERR_SQLITE);
				result.SetSQLiteResult(rcprepare);

			}


		}



		return result;
	}






};





#include "namespace_end.h"


#pragma comment(lib,"sqlite3.lib")
