g_DictMgr = {}

function NewCppSqlite()
	local SqliteDB = newCppSqlite()
	openSqlite(SqliteDB, getRootPath().."/QQRobots.db")
	return SqliteDB
end

function FreeCppSqlite(SqliteDB)
	close(SqliteDB)
	freeCppSqlite(SqliteDB)
end

function g_DictMgr.InitDict()
	local SqliteDB = NewCppSqlite()

	if tableExists(SqliteDB, "DictMgr")==false then
		local strSql = [[
		CREATE TABLE [DictMgr] (
			[ID] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,
			[Question] TEXT  NULL,
			[Answer1] TEXT  NULL,
			[Answer2] TEXT  NULL,
			[Answer3] TEXT  NULL
			) ]]
			
		local result = execSQL(SqliteDB, strSql)
		print("g_DictMgr.InitDict Create Table [DictMgr]: "..tostring(result))
	end
	
	FreeCppSqlite(SqliteDB)
end


g_DictMgr.InitDict()


g_DictAllDatas = {}

function LFLoadAllDatas()
	g_DictAllDatas = {}
	
	local SqliteDB = NewCppSqlite()
	local strSql = "select * from DictMgr order by ID"
	local tData = getTable(SqliteDB, strSql)
	local nums = numRows(tData)
	for i=1, nums, 1 do
		setRow(tData, i-1)
		local o = {}
		o[1] = fieldValueByID(tData, 1)
		o[2] = fieldValueByID(tData, 2)
		o[3] = fieldValueByID(tData, 3)
		o[4] = fieldValueByID(tData, 4)
		table.insert(g_DictAllDatas, o)
	end
	
	FreeCppSqlite(SqliteDB)
end


function LFSaveAllDatas()
	local SqliteDB = NewCppSqlite()
	local strSql = "delete from DictMgr"
	execSQL(SqliteDB, strSql)
	
	for _,v in ipairs(g_DictAllDatas) do
		if v[1]~=nil then
			local strFormat = [[insert into DictMgr(Question, Answer1, Answer2, Answer3) 
				values ('%s', '%s', '%s', '%s')]]
			local strSql = string.format(strFormat, v[1], v[2], v[3], v[4])
			print("LFSaveAllDatas: "..strSql)
			execSQL(SqliteDB, strSql)
		end
	end

	FreeCppSqlite(SqliteDB)
end

function LFGetRecordRowCount()
	return #g_DictAllDatas
end

function LFGetRecordValue(row, col)
	return g_DictAllDatas[row][col]
end

function LFAddNewRecord(ques, ans1, ans2, ans3)
	table.insert(g_DictAllDatas, {ques, ans1, ans2, ans3})
	return #g_DictAllDatas
end

function LFDelRecord(index)
	table.remove(g_DictAllDatas, index)
end

function LFUpdateRecord(index, ques, ans1, ans2, ans3)
	g_DictAllDatas[index] = {ques, ans1, ans2, ans3}
end

function LFClearAllRecords()
	g_DictAllDatas={}
end


function g_DictMgr.GetAnswerWords(szText)
	if #g_DictAllDatas==0 then
		LFLoadAllDatas()
	end
	
	for _,v in ipairs(g_DictAllDatas) do
		local ques = v[1]
		local i, j = string.find(szText, ques)
		if i~=nil and j~=nil and j>i then
			local o = {}
			if v[2]~=nil and string.len(v[2])>0 then
				table.insert(o, v[2])
			end
			
			if v[3]~=nil and string.len(v[3])>0 then
				table.insert(o, v[3])
			end
			
			if v[4]~=nil and string.len(v[4])>0 then
				table.insert(o, v[4])
			end
			
			local ii = math.random(1, #o)
			return o[ii]
		end
	end
	return nil
end
