g_ChatLogDB = {}
g_ChatLogDB.QQMessages = {}
g_ChatLogDB.AllMembersInfo = {}
g_ChatLogDB.AllChatMsgInfo = {}


function g_ChatLogDB.InitDict()
	local SqliteDB = NewCppSqlite()
	
	if tableExists(SqliteDB, "ChatLogMgr")==false then
		local strSql = [[
		CREATE TABLE [ChatLogMgr] (
			[ID] INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL,
			[QQNumber1] INTEGER  NOT NULL,
			[QQNickName1] NVARCHAR(64)  NOT NULL,
			[QQNumber2] INTEGER  NOT NULL,
			[QQNickName2] NVARCHAR(64)  NOT NULL,
			[MsgTime] NVARCHAR(32)  NOT NULL,
			[Content] TEXT  NULL
			) ]]
			
		local result = execSQL(SqliteDB, strSql)
		print("g_ChatLogDB.InitDict Create Table [ChatLogMgr]: "..tostring(result))
	end
	
	FreeCppSqlite(SqliteDB)
end

g_ChatLogDB.InitDict()


function LFLoadAllMembersInfo()
	local SqliteDB = NewCppSqlite()

	g_ChatLogDB.AllMembersInfo = {}
	if g_BuddyMsgMgr.UserInfo[1]==nil then return end
	
	local strSql = string.format("select QQNumber1, QQNickName1, max(MsgTime) as MsgTime, 2*count(*) as Count from ChatLogMgr where QQNumber2=%u group by QQNumber1",
		g_BuddyMsgMgr.UserInfo[1])
	local tData = getTable(SqliteDB, strSql)
	local nums = numRows(tData)
	for i=1, nums, 1 do
		setRow(tData, i-1)
		local o = {}
		for j=1, 4, 1 do
			o[j] = fieldValueByID(tData, j-1)
		end
		table.insert(g_ChatLogDB.AllMembersInfo, o)
	end

	FreeCppSqlite(SqliteDB)
end


function LFLoadAllChatMsgInfo(nQQNum)
	
	local SqliteDB = NewCppSqlite()

	g_ChatLogDB.AllChatMsgInfo = {}
	local strSql = string.format("select * from ChatLogMgr where QQNumber1==%u or QQNumber2==%u",nQQNum,nQQNum)
	local tData = getTable(SqliteDB, strSql)
	local nums = numRows(tData)
	for i=1, nums, 1 do
		setRow(tData, i-1)
		local o = {}
		for j=1, 6, 1 do
			o[j] = fieldValueByID(tData, j)
		end
		table.insert(g_ChatLogDB.AllChatMsgInfo, o)
	end

	FreeCppSqlite(SqliteDB)
end

function LFGetMembersInfoRecordRowCount()
	return #g_ChatLogDB.AllMembersInfo
end

function LFGetMembersInfoRecordValue(row, col)
	return g_ChatLogDB.AllMembersInfo[row][col]
end

function LFGetChatMsgInfoRecordRowCount()
	return #g_ChatLogDB.AllChatMsgInfo
end

function LFGetChatMsgInfoRecordValue(row, col)
	return g_ChatLogDB.AllChatMsgInfo[row][col]
end


function g_ChatLogDB.AddMessageDB(nQQNum1, nickName1, nQQNum2, nickName2, szTime, szText)
	table.insert(g_ChatLogDB.QQMessages, {nQQNum1, nickName1, nQQNum2, nickName2, szTime, szText})
end

function g_ChatLogDB.SaveToDB()
	local SqliteDB = NewCppSqlite()
	
	for _,v in ipairs(g_ChatLogDB.QQMessages) do
		local strSql = string.format("insert into ChatLogMgr(QQNumber1, QQNickName1, QQNumber2, QQNickName2, MsgTime, Content) \
			values (%u, '%s', %u, '%s', '%s', '%s')", v[1], v[2], v[3], v[4], v[5], v[6])
		execSQL(SqliteDB, strSql)
	end
	g_ChatLogDB.QQMessages={}

	FreeCppSqlite(SqliteDB)
end


function g_ChatLogDB.AutoWriteToDB()
	local co = moc.createCo(function ()
		while true do
			moc.sleep(1000*60)
			g_ChatLogDB.SaveToDB()
		end
	end)
end

g_ChatLogDB.AutoWriteToDB()