local default_thres = 1200
local shown = false

function GetAddinPath()
	local PathTool = XLGetObject("Xunlei.Thunder.Path")
	local path = PathTool:GetProfilesPath() .. "AccSaveTimeTip\\"
	local shell = XLGetObject("Xunlei.UIEngine.OSShell")
	
	if not shell:QueryFileExists(path) then
		shell:CreateDir(path)
	end
	
	return path
end

function GetDataFilePath()
	return GetAddinPath().."data.xml"
end

function ReadAccData()
--XLMessageBox("ReadAccData:9")
	local xldata = XLGetObject("Xunlei.XLData")
	local datalist = xldata:GetTableFromXML(GetDataFilePath())
--XLMessageBox("ReadAccData:12")
	if datalist ~= nil then
		return tonumber(datalist["AccSaveTimeTip"]["DownloadTime"]),tonumber(datalist["AccSaveTimeTip"]["SaveTime"]),tonumber(datalist["AccSaveTimeTip"]["DeadLink"])
	else
		return 0,0,0
	end
end

function GetPieImgId(percent)
	local i=1
	if percent <= 10 then
		i = 1
	elseif percent <= 20 then
		i = 2
	elseif percent <= 30 then
		i = 3
	elseif percent <= 40 then
		i = 4
	elseif percent <= 50 then
		i = 5
	elseif percent <= 60 then
		i = 6
	elseif percent <= 70 then
		i = 7
	elseif percent <= 80 then
		i = 8
	elseif percent <= 90 then
		i = 9
	else
		i = 10
	end
	
	return "bitmap.accsavetimetip.pie." .. i
end

function IsVip()
	local objXLUser = XLGetObject("Xunlei.XLUser.Factory")
	if not objXLUser then
		return false
	end
	local oXLUser = objXLUser:CreateInstance()
	local islogin = oXLUser:IsLogIn()
	if not islogin then
		return false
	end
	
	local user_info = oXLUser:GetUserInfo()
	if user_info == nil then
	    return false
	end
	local vip_info = oXLUser:GetUserVipInfo()
	if vip_info == nil then
		return false
	end
	return vip_info:GetIsVip() ~= 0
end

function MoveObj( obj , newleft, newtop)
	local left,top,right,bottom = obj:GetObjPos()
	local width = right - left
	local height = bottom - top
	
	obj:SetObjPos( newleft, newtop, newleft+width, newtop+height)
end

function FormatTime(val)
    if val >= 24 * 365 then
		return ""..math.floor(val/(24*365)).."年"
	elseif val>= 24*30 then
		return ""..math.floor(val/(24*30)).."个月"
	elseif val>= 24*7 then
		return ""..math.floor(val/(24*7)).."周"
	elseif val>= 24 then
		return ""..math.floor(val/(24)).."天"
	else
		return ""..val.."小时"
	end
end

function OnCreateFunc(treectrl) -- 必须在 notifyHelp:ShowPopupTip 前面？
--XLMessageBox("OnCreateFunc0")
	if treectrl == nil then
		return 
	end
--XLMessageBox("OnCreateFunc")	
	local DownloadTime, SaveTime, DeadLink = ReadAccData()
	if SaveTime > 0 then -- pop! Fixme!
		-- 根据IsVip 决定 下半部 obj 的text, 位置，显示与否, wnd size
		local title = treectrl:GetUIObject("root.layout:Title")
		local msg2 = treectrl:GetUIObject("root.layout:Msg2")
		local msg3 = treectrl:GetUIObject("root.layout:Msg3")
		local link1 = treectrl:GetUIObject("root.layout:Link1")
		local button1 = treectrl:GetUIObject("root.layout:Button1")
		
		if IsVip() == true then
			title:SetText("尊敬的迅雷会员")
			msg2:SetVisible(false)
			msg3:SetVisible(false)
			button1:Show(false)
			link1:SetText("了解更多会员特权")
			MoveObj( link1 , 15+5+5, 154-3)
		else	
			title:SetText("尊敬的迅雷用户")
			MoveObj( link1 , 15+5+5, 203-3)
			msg2:SetVisible(true)
			msg3:SetVisible(true)
			button1:Show(true)
			link1:SetText("更多特权")
		end
		-- 动态设置 info text, pie graph
		local percent = math.floor(100*SaveTime / (DownloadTime+SaveTime))
		local InfoTime = treectrl:GetUIObject("root.layout:InfoTime")	
		local InfoPercent = treectrl:GetUIObject("root.layout:InfoPercent")	
		local InfoDead = treectrl:GetUIObject("root.layout:InfoDead")	
		local pie = treectrl:GetUIObject("root.layout:Pie")	
		SaveTime = math.floor(SaveTime / 3600)
		InfoTime:SetText(FormatTime(SaveTime))
		InfoPercent:SetText(""..percent.."%")
		InfoDead:SetText(""..DeadLink.."个")
		pie:SetResID(GetPieImgId(percent))
	end
end

function CalcCurrentData(basicTask, task, taskExtra)
	local DownloadTime = 0
	local SaveTime = 0
	local DeadLink = 0
	if taskExtra ~= nil then
--XLMessageBox("CalcCurrentData : 110")
		local hr, chanelblockinfo = taskExtra:GetChannelInfo()
		--local hr, blockcount = chanelblockinfo:GetBlockCount()
		
		local hr, originalsize = chanelblockinfo:GetOriginChannelDownloadSize()
		local hr, p2psize = chanelblockinfo:GetCommonP2pChannelDownloadSize()
		local hr, mirrorsize = chanelblockinfo:GetCommonP2sChannelDownloadSize()
		local hr, highsize = chanelblockinfo:GetVipChannelDownloadSize()
		local hr, offlinesize = chanelblockinfo:GetOfflineChannelDownloadSize()
		
		local hr, statusDetail = task:GetStatusDetail()
		local hr, fileSize = statusDetail:GetResourceSize()
		local hr, recvSize = statusDetail:GetTotalReceiveValidSize()
		local hr, speed = statusDetail:GetDownloadSpeed()
		local hr, period = statusDetail:GetDownloadingPeriod()
		local hr, remainPeriod = statusDetail:GetRemainderPeriod()
		
		DownloadTime = period
		if originalsize ~= 0 and recvSize ~= 0 then
			--Downloadtime = period  -- Wrong !
			SaveTime = math.floor((fileSize / originalsize - fileSize/recvSize) * period)	-- Fixme?
		elseif recvSize ~= 0 then
			DeadLink  = 1 -- 解决的
		end
--XLMessageBox("CalcCurrentData : 133")		
	end
	
	return DownloadTime, SaveTime, DeadLink
end

function WriteAccData(downloadTime, saveTime, deadLink)
	local datalist = {}
	datalist["AccSaveTimeTip"] = {}
	datalist["AccSaveTimeTip"]["DownloadTime"] = downloadTime
	datalist["AccSaveTimeTip"]["SaveTime"] = saveTime
	datalist["AccSaveTimeTip"]["DeadLink"] = deadLink
	
	local xldata = XLGetObject("Xunlei.XLData")
	xldata:SaveTableToXML(GetDataFilePath(), datalist)
end

function GetPower(num, div)
	if num < div then
		return -1
	end
	num = num / div
	local power = 0 -- power of 2!
	while num >= 2 do
		num = num / 2
		power = power + 1
	end
	return power
end

function OnTaskDownloadComplete(basicTask, task, taskExtra)
--XLMessageBox("OnTaskDownloadComplete")
	local iDownloadTime,iSaveTime,iDeadLink = CalcCurrentData(basicTask, task, taskExtra)
	if iDownloadTime + iSaveTime + iDeadLink > 0 then  
		local xlConfig = XLGetObject("Xunlei.Thunder.Config")
		local thres = xlConfig:GetValue("AccSaveTimeTip", "PopThreshold",default_thres)
		
		local DownloadTime, SaveTime, DeadLink = ReadAccData()

		local OldPow = GetPower(SaveTime / 60, thres)
		
		DownloadTime = math.min(DownloadTime + iDownloadTime, 0xEFFFFFFF)
		SaveTime = math.min(SaveTime + iSaveTime, 0xEFFFFFFF)
		DeadLink = math.min(DeadLink + iDeadLink, 0xEFFFFFFF)
		-- pop?	
		WriteAccData(DownloadTime, SaveTime, DeadLink) -- for OnCreateFunc()
		
		local pow = GetPower(SaveTime / 60, thres)
		if  pow ~= OldPow  and DeadLink > 0 and not(shown) then -- pop! Fixme!
		-- 创建窗口 + objtree
			local notifyHelp = XLGetGlobal("xunlei.LuaNotifyHelper")
			notifyHelp:ShowPopupTip("AccSaveTimeTipUniqueID","AccSaveTimeTipTree","AccSaveTimeTipType",OnCreateFunc)
			shown = true
		end
	end
end

function GetCfgXMLPath()
	return GetAddinPath().."config.xml"
end

function file_on_ready(id,url,file,status)
	--http文件下载成功事件
	local xlConfig = XLGetObject("Xunlei.Thunder.Config")
	--if status == 0 then --文件有更新
		local xldata = XLGetObject("Xunlei.XLData")
		local datalist = xldata:GetTableFromXML(GetCfgXMLPath())
		--XLMessageBox("update")
		if datalist ~= nil then
			xlConfig:SetValue("AccSaveTimeTip", "PopThreshold", tonumber(datalist["AccSaveTimeTip"]["Threshold"] or default_thres))
		end
	--end
end

function FetchPopThreshold()
	local timer_manager = XLGetObject("Xunlei.UIEngine.TimerManager")
	timer_manager:SetTimer( function ( itm, id )
								timer_manager:KillTimer( id )
								local f = XLGetObject("xl.win32.net.asyn_http_file.factory")
								local http = f.create_instance()
								local r = http:attach_event("on_asyn_http_file_ready", file_on_ready)
								local headers = {}
								--headers["Connection"]="close"
								r = http:request_file(0,"http://skin.client.xunlei.com/thunder7/acc/AccSaveTimeTip.xml", headers, GetCfgXMLPath() ) -- Fixme
							end, 1000 )
end

----- statements block begin
local downloadKernel = XLGetObject("Xunlei.DownloadKernel.DownloadKernel")
local hr, taskMgr = downloadKernel:GetTaskMgr()

local xlConfig = XLGetObject("Xunlei.Thunder.Config")
xlConfig:SetValue("AccSaveTimeTip", "PopThreshold", default_thres) -- default

--- testing ....
--local notifyHelp = XLGetGlobal("xunlei.LuaNotifyHelper")
--notifyHelp:ShowPopupTip("AccSaveTimeTipTree","testType",OnCreateFunc)
---- testing....

local hr, taskStatusDetailChangedEventCookie = taskMgr:AttachTaskStatusDetailEvent("StatusDetailChanged",
			function (targetTaskStatusDetail, changedFlags)
				local hr, task = targetTaskStatusDetail:GetTask()
				local hr, basicTask = task:GetBasic()
				local hr, status = basicTask:GetStatus()
				if status == 8 then	--TS_Succeeded
					--任务下载完成
					local hr, taskExtra = task:GetExtra()
					if taskExtra ~= nil then
						OnTaskDownloadComplete(basicTask, task, taskExtra)
					else
						function OnTaskBasicLoadComplete(target)
							hr, taskExtra = task:GetExtra()
							OnTaskDownloadComplete(basicTask, task, taskExtra)
						end
						basicTask:LoadAsync(true, OnTaskBasicLoadComplete, 0)
					end
				end
			end
)

FetchPopThreshold()
----- statements block end
---

function FormatTime2(val)
	local des = ""
	local n
	if val >= 24 * 60 * 60 then
		n = math.floor(val/(365 * 24 * 60 * 60))
		val = math.fmod(val, 365 * 24 * 60 * 60)
		if n > 0 then
			des = des .. n .. "年"
		end
		n = math.floor(val/(30 * 24 * 60 * 60))
		val = math.fmod(val, 30 * 24 * 60 * 60)
		if n > 0 then
			des = des .. n .. "月"
		end
		n = math.floor(val/(7 * 24 * 60 * 60))
		val = math.fmod(val, 7 * 24 * 60 * 60)
		if n > 0 then
			des = des .. n .. "周"
		end
		n = math.floor(val/(24 * 60 * 60))
		if n > 0 then
			des = des .. n .. "天"
		end
	else
		n = math.floor(val/(60 * 60))
		val = math.fmod(val, 60 * 60)
		if n > 0 then
			des = des .. n .. "时"
		end
		n = math.floor(val/(60))
		val = math.fmod(val, 60)
		if n > 0 then
			des = des .. n .. "分"
		end
		if val > 0 then
			des = des .. val .. "秒"
		end
	end
	if des == "" then
		return "0秒"
	else
		return des
	end
end

function OnCreateFunc2(self)
	if self == nil then
		return 
	end
	self:BringWindowToTop( true )
	local treectrl = self:GetBindUIObjectTree()
	local DownloadTime, SaveTime, DeadLink = ReadAccData()
	
	-- 根据IsVip 决定 下半部 obj 的text, 位置，显示与否, wnd size
	local title = treectrl:GetUIObject("Title")
	local msg2 = treectrl:GetUIObject("Msg2")
	local msg3 = treectrl:GetUIObject("Msg3")
	local link1 = treectrl:GetUIObject("Link1")
	local button1 = treectrl:GetUIObject("Button1")
	
	if IsVip() == true then
		title:SetText("尊敬的迅雷会员")
		msg2:SetVisible(false)
		msg3:SetVisible(false)
		button1:Show(false)
		link1:SetText("了解更多会员特权")
		MoveObj( link1 , 26, 154-3)
	else	
		title:SetText("尊敬的迅雷用户")
		MoveObj( link1 , 26, 203-3)
		msg2:SetVisible(true)
		msg3:SetVisible(true)
		button1:Show(true)
		link1:SetText("更多特权")
	end
	-- 动态设置 info text, pie graph
	local percent = math.floor(100*SaveTime / (DownloadTime+SaveTime))
	local InfoTime = treectrl:GetUIObject("InfoTime")	
	local InfoPercent = treectrl:GetUIObject("InfoPercent")	
	local InfoDead = treectrl:GetUIObject("InfoDead")	
	local pie = treectrl:GetUIObject("Pie")	
	--SaveTime = math.floor(SaveTime / 3600)
	InfoTime:SetText(FormatTime2(SaveTime))
	InfoPercent:SetText(""..percent.."%")
	InfoDead:SetText(""..DeadLink.."个")
	pie:SetResID(GetPieImgId(percent))
	
	local saveTimeTextWidth = InfoTime:GetTextExtent()
	local l, t, r, b = InfoTime:GetObjPos()
	local dif = r - l - saveTimeTextWidth
	InfoTime:SetObjPos(l, t, r - dif, b)
	local obj = treectrl:GetUIObject("root.layout")
	l, t, r, b = obj:GetObjPos()
	obj:SetObjPos(l, t, r - dif, b)
	obj = treectrl:GetUIObject("BoxBkg")
	l, t, r, b = obj:GetObjPos()
	obj:SetObjPos(l, t, r - dif, b)
	obj = treectrl:GetUIObject("Pie")
	l, t, r, b = obj:GetObjPos()
	obj:SetObjPos(l - dif, t, r - dif, b)
	obj = treectrl:GetUIObject("Button1")
	l, t, r, b = obj:GetObjPos()
	obj:SetObjPos(l - dif, t, r - dif, b)
end

function EventFunc()
	shown = true
	local hostWndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local parentWnd = hostWndManager:GetHostWnd("Thunder.MainFrame")
	local hostWndHelp = XLGetGlobal("xunlei.LuaHostWndHelper")
	hostWndHelp:DoModal("AccSaveTimeDlg", "AccSaveTimeTipTree2", parentWnd, OnCreateFunc2)
end

local multiEventHelper = XLGetGlobal("xunlei.MultiEventHelper")
if multiEventHelper then
	multiEventHelper.AttachEvent("AccSaveTime", EventFunc)
end



