--lua文件必须是UTF-8编码的(最好无BOM头)
local myClass
local progressTimer
local initTimer
local rememberPosTimer
local myClassFactory
local m_currentSong
local record
local m_lasturl
local m_currentPage
local m_pages = {"home.aspx", "Radio.aspx", "Broadcast.aspx", "Novel.aspx", "Other.aspx"}
local loadingUrl
local errorUrl
local webTitle

function btnclose_OnClick(self)
	doQuit();
end

---程序退出的工作
function doQuit(self)
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local playSliderBar = objtree:GetUIObject("playSliderBar")
	local volumeSliderBar = objtree:GetUIObject("volumeSliderBar")
	--保存当前播放的曲目和音量
	myClass:RecordSet((m_currentSong and m_currentSong.parent.data) or "0",  --这个就是ID，我日
					string.format("%d", (m_currentSong and m_currentSong.index) or 0), 
					string.format("%d", playSliderBar:GetValue()),
					string.format("%d", volumeSliderBar:GetValue()))
	myClass:Quit(0)
	
	hostwndManager:RemoveHostWnd("Wizard.MainWnd.Instance")

	local objtreeManager = XLGetObject("Xunlei.UIEngine.TreeManager")	
	objtreeManager:DestroyTree("Wizard.MainObjTree.Instance")

	local app = XLGetObject("Wizard.App")
	app:Quit(0)
	----os.exit 效果等同于windows的exit函数，不推荐实际应用中直接使用
	os.exit()	
end


function OnClose(self)
--	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
--	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
--	hostwnd:SetVisible(false)
	doQuit();
	return 1, true
end

function OnInitControl(self)
	local owner = self:GetOwner()
	
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	
	Refresh(owner)
end

function MSG_OnMouseMove(self)
	self:SetTextFontResID ("msg.font.bold")
	self:SetCursorID ("IDC_HAND")
end

function MSG_OnMouseLeave(self)
	self:SetTextFontResID ("msg.font")
	self:SetCursorID ("IDC_ARROW")
end

function userdefine_btn_OnClick(self)
	XLMessageBox("Click on button")
end

function treeview_OnSelectChanged(self,fun,item)
	--local attr = item:GetAttribute()
	--if attr.itemattr.path ~= nil then
	--	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
		--local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
		--local objtree = hostwnd:GetBindUIObjectTree()
		--local btnplay = objtree:GetUIObject("btnplay")
		--m_currentSong = attr.itemattr
		--btnplay:Click();
	--end
end

function treeview_OnDoubleClicked(self,fun,item)
	if item == nil then
		return
	end
	
	local attr = item:GetAttribute()
	if attr.itemattr.path ~= nil then
		local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
		local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
		local objtree = hostwnd:GetBindUIObjectTree()
		local playSliderBar = objtree:GetUIObject("playSliderBar")
		playSliderBar:SetProgressValue(0,1,0,true)
		local treeview = objtree:GetUIObject("treeview")
		local btnplay = objtree:GetUIObject("btnplay")
		m_currentSong = attr.itemattr
		treeview:SetExpandAllButOne(m_currentSong.parent)
		btnplay:Click();
	end
end

function btnmin_OnClick(self)
--	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
--	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
--	hostwnd:Min()
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	hostwnd:SetVisible(false)
end

function AddTreeNodeItem(self,level,title,data1,data2)
	if level == 0 then
		AddAblumNodeItem(self,title,data1,data2)
		Show();
	else
		AddSongNodeItem(self,title,data1,data2)
	end
end

function AddAblumNodeItem(self,title,id,count)
	local treeview = self:GetUIObject("treeview")
	local root = treeview:GetRootItem()
	local obj1 = treeview:InsertItemText(title,id,root)
	obj1.color = "system.white"
	treeview:SetExpand(obj1,false)
	treeview:SetAdjust()
end

function AddSongNodeItem(self,title,path,state)
	local treeview = self:GetUIObject("treeview")
	local root = treeview:GetRootItem()
	lastItem = treeview:GetChildItemByIndex(root,treeview:GetChildrenItemCount(root))
	local obj1 = treeview:InsertSongNode(title,path,lastItem)
	obj1.color = "system.white"
	treeview:SetAdjust()
end

function PlayNode(self,id,set)
	local treeview = self:GetUIObject("treeview")
	local root = treeview:GetRootItem()
	item = treeview:GetChildItemByID(root,id)
	if item ~= nil then
		m_currentSong = item.children[#set]
		treeview:SetSelected(m_currentSong, true)
		treeview:SetExpandAllButOne(m_currentSong.parent)
		local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
		local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
		local objtree = hostwnd:GetBindUIObjectTree()
		local btnplay = objtree:GetUIObject("btnplay")
		btnplay:Click();
	end
	--treeview:ItemClick(item)
end

-------------------------------------------------------
-- 参数:待分割的字符串,分割字符
-- 返回:子串表.(含有空串)
function lua_string_split(str, split_char)
    local sub_str_tab = {};
    while (true) do
        local pos = string.find(str, split_char);
        if (not pos) then
            sub_str_tab[#sub_str_tab + 1] = str;
            break;
        end
        local sub_str = string.sub(str, 1, pos - 1);
        sub_str_tab[#sub_str_tab + 1] = sub_str;
        str = string.sub(str, pos + 1, #str);
    end

    return sub_str_tab;
end

function Refresh(owner)
	if myClass == nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	
	loadingUrl = string.format("%s%s", myClass:GetAppPath(), "\\html\\loading.html");
	errorUrl = string.format("%s%s", myClass:GetAppPath(), "\\html\\error.html");
	
	myClass:AttachAddTreeNodeListener(function(level,title,data1,data2) AddTreeNodeItem(owner,level,title,data1,data2) end)
	myClass:AttachPlayNodeListener(function(id,set) PlayNode(owner,id,set) end)
	myClass:AttachMsgListener(function(flag,data) Msg(owner,flag,data) end)
	myClass:AttachCloseListener(function() Close(owner) end)
	myClass:AttachShowListener(function() Show(owner) end)
	
	--读入历史播放列表
	myClass:ReadHistory()
	progressTimerFactory  = XLGetObject("Xunlei.UIEngine.TimerManager")
	initTimer = progressTimerFactory:SetTimer(onLoadLastRecord, 500)
end

function onLoadLastRecord()
	progressTimerFactory  = XLGetObject("Xunlei.UIEngine.TimerManager")
	progressTimerFactory:KillTimer(initTimer)
	
	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	--读入历史播放记录
	local lastRecord = myClass:ReadLast()

	--初始化m_currentSong
	progressTimerFactory  = XLGetObject("Xunlei.UIEngine.TimerManager")
	
	record = string_split(lastRecord, ',')
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local treeview = objtree:GetUIObject("treeview")
	local root = treeview:GetAttribute().root
	local volumeSliderBar = objtree:GetUIObject("volumeSliderBar")
	if tonumber(record[1]) == 0 then --播放列表为空
		if treeview:GetChildrenItemCount(root) > 0 then
			local album = treeview:GetChildItemByIndex(root, 1)
			treeview:SetExpand(album, true, true)
			m_currentSong = treeview:GetChildItemByIndex(album, 1)
			treeview:SetSelected(m_currentSong, true)
		end
	else
		local album = treeview:GetChildItemByID(root, record[1])
		if album ~= nil then
			treeview:SetExpand(album, true, true)
			m_currentSong = treeview:GetChildItemByIndex(album, tonumber(record[2]))
			treeview:SetSelected(m_currentSong, true)
			--设置pos 为record[3]
			--继续上次播放
			local btnplay = objtree:GetUIObject("btnplay")
			btnplay:Click()
			--myClass:SetVolume(0)  --暂时静音
			rememberPosTimer = progressTimerFactory:SetTimer(OnRemberPos,200)
		end
	end
	
	--设置volume,标题等
	volumeSliderBar:SetProgressValue(0, 100, tonumber(record[4]), true)
	myClass:SetVolume(tonumber(record[4]))
	if m_currentSong ~= nil then
		local songTitle = objtree:GetUIObject("songTitle")
		local songAuthor = objtree:GetUIObject("songAuthor")
		songTitle:SetText(m_currentSong.parent.txt.."  "..m_currentSong.txt)
		songAuthor:SetText(m_currentSong.txt)
	end
	progressTimer = progressTimerFactory:SetTimer(OnPlayProgress,1000)
end

function OnRemberPos()
	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	if myClass:GetPlayerStateStr() == "正在播放 ..." then
		--myClass:Pause()
		myClass:SetPosition(tonumber(record[3]))
		progressTimerFactory  = XLGetObject("Xunlei.UIEngine.TimerManager")
		progressTimerFactory:KillTimer(rememberPosTimer)
		--local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
		--local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
		--local objtree = hostwnd:GetBindUIObjectTree()
		--local btnplay = objtree:GetUIObject("btnplay")
		--btnplay:ChangeState(2,-1)
		--local playSliderBar = objtree:GetUIObject("playSliderBar")
		--local currentPos = objtree:GetUIObject("currentPos")
		--local totalDur = objtree:GetUIObject("totalDur")
		--playSliderBar:SetProgressValue(0, myClass:GetDuration(), tonumber(record[3]), true)
		--local dur = myClass:GetDuration()
		--totalDur:SetText(string.format("%02d:%02d",math.floor(dur/60),math.floor(dur%60)))
		--local pos = myClass:GetPosition()
		--currentPos:SetText(string.format("%02d:%02d",math.floor(pos/60),math.floor(pos%60)))
	end
end

---------------字符串分割函数
-- 参数:待分割的字符串,分割字符
-- 返回:子串表.(含有空串)
function string_split(str, split_char)
    local sub_str_tab = {};
    while (true) do
        local pos = string.find(str, split_char);
        if (not pos) then
            sub_str_tab[#sub_str_tab + 1] = str;
            break;
        end
        local sub_str = string.sub(str, 1, pos - 1);
        sub_str_tab[#sub_str_tab + 1] = sub_str;
        str = string.sub(str, pos + 1, #str);
    end

    return sub_str_tab;
end

function Msg(owner,flag,data)
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	if flag =="连接状态" then
		local playState = objtree:GetUIObject("playState")
		playState:SetText(data)
	end
end

function Close(owner)
	doQuit();
end

function Show(owner)
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	hostwnd:SetVisible(true)
	hostwnd:Restore()
	hostwnd:BringWindowToTop(true)
end

function alphaSliderBar_OnScroll(self, fun, type, pos, value)
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local image = hostwnd:GetControlObject("Player.bkg")
	image:SetAlpha(self:GetValue()/100 * 255)
end

function volumeSliderBar_OnScroll(self, fun, type, pos, value)
	if myClass ~=nil  then
		myClass:SetVolume(value)
	end
	local owner = self:GetOwner()
	local btnsound = owner:GetUIObject("btnsound")
	btnsound:ChangeState(2,-1)
end

function volumeSliderBar_OnMouseWheel(self,x,y,distance)

end

function playSliderBar_OnScroll(self, fun, type, pos, value)
	if type ~=1 then
		return
	end
	if myClass ~=nil  then
		myClass:SetPosition(value)
	end
end

function playSliderBar_OnMouseWheel(self,x,y,distance)

end

function btnplay_OnClick(self)
	if m_currentSong == nil or m_currentSong.parent.data == 0 then
		return
	end
	Play(self)
end

function Play(self)
	if m_currentSong == nil or m_currentSong.parent.data == 0 then
		return
	end

	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local songTitle = objtree:GetUIObject("songTitle")
	local songAuthor = objtree:GetUIObject("songAuthor")
	local url = m_currentSong.path
	songTitle:SetText(m_currentSong.parent.txt.."  "..m_currentSong.txt)
	songAuthor:SetText(m_currentSong.txt)
	local state = myClass:GetState()
	if m_lasturl ~=url then
		local btnplay = objtree:GetUIObject("btnplay")
		btnplay:ChangeState(2,-1)
		m_lasturl = url
		myClass:Play(url)
		return
	end
	if state == 0 then
		myClass:Play(url)
	elseif state == 1 or state == 2 then
		myClass:Pause()
	end
end

function PlayByUrl(url)
	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	local state = myClass:GetState()
	if state == 0 then
		--myClass:Play("http://www.365ting.com"..url)
		myClass:Play(url)
		--progressTimerFactory  = XLGetObject("Xunlei.UIEngine.TimerManager")
		--rogressTimer = progressTimerFactory:SetTimer(OnPlayProgress,1000)
	elseif state == 1 or state == 2 then
		myClass:Pause()
	end
end

function OnPlayProgress()
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	if objtree == nil then return end
	local currentPos = objtree:GetUIObject("currentPos")
	local totalDur = objtree:GetUIObject("totalDur")
	local playSliderBar = objtree:GetUIObject("playSliderBar")
	if playSliderBar:GetTrackMouse() then
		return
	end
	
	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	if myClass:wantToClose() == 1 then --关闭
		local btnclose = objtree:GetUIObject("btnclose")
		btnclose:FireExtEvent("OnClick")
		return
	end
	
	local playState = objtree:GetUIObject("playState")
	local data = myClass:GetPlayerStateStr()
	playState:SetText(data) --播放状态
	
	local state = myClass:GetState()
	if state == 2 then
		local dur = myClass:GetDuration()
		totalDur:SetText(string.format("%02d:%02d",math.floor(dur/60),math.floor(dur%60)))
		local pos = myClass:GetPosition()
		playSliderBar:SetProgressValue(0,dur,pos,true)
		currentPos:SetText(string.format("%02d:%02d",math.floor(pos/60),math.floor(pos%60)))
	elseif state == 0  or state == 4 then
		totalDur:SetText("00:00")
		currentPos:SetText("00:00")
		playSliderBar:SetProgressValue(0,1,0,true)
		local btnplay = objtree:GetUIObject("btnplay")
		btnplay:ChangeState(2,-1)
		if state == 4 then --下一曲
			btnnext_OnClick()
		end
	end
end

function btnstop_OnClick(self)
	if myClass ~=nil  then
		local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
		local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
		local objtree = hostwnd:GetBindUIObjectTree()
		if objtree == nil then return end
		local currentPos = objtree:GetUIObject("currentPos")
		local totalDur = objtree:GetUIObject("totalDur")
		local playSliderBar = objtree:GetUIObject("playSliderBar")
		myClass:Stop()
		totalDur:SetText("00:00")
		currentPos:SetText("00:00")
		playSliderBar:SetProgressValue(0,1,0,true)
		local owner = self:GetOwner()
		local btnplay = owner:GetUIObject("btnplay")
		btnplay:ChangeState(2,-1)
	end
end

function btnprev_OnClick(self)
	if m_currentSong == nil or m_currentSong.parent.data == 0 then
		return
	end
	
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local tree = objtree:GetUIObject("treeview")
	if m_currentSong.index > 1 then
		local item = m_currentSong.parent.children[m_currentSong.index - 1]
		tree:SetSelected(item, true)
		tree:FireExtEvent("OnDoubleClicked", item.obj)
	end
end

function btnnext_OnClick(self)
	if m_currentSong == nil or m_currentSong.parent.data == 0 then
		return
	end
	
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
	local objtree = hostwnd:GetBindUIObjectTree()
	local tree = objtree:GetUIObject("treeview")
	if m_currentSong.index < #m_currentSong.parent.children then
		local item = m_currentSong.parent.children[m_currentSong.index+1]
		tree:SetSelected(item, true)
		tree:FireExtEvent("OnDoubleClicked", item.obj)
	end
end

function btnsound_OnClick(self)
	if myClass ~=nil then
		if	self:GetTick() == -1 then
			myClass:SetVolume(0)
		else
			local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
			local hostwnd = hostwndManager:GetHostWnd("Player.Wnd")
			local objtree = hostwnd:GetBindUIObjectTree()
			local volumeSliderBar = objtree:GetUIObject("volumeSliderBar")
			myClass:SetVolume(volumeSliderBar:GetValue())
		end
	end
end

function OnNavigateComplete2(self, url)
	local locationName = self:GetLocationName()
	if string.find(url, "loading.html") ~= nil then
		local urlCurr = string.format("%s%s", "http://www.tingshijie.com:8001/", m_pages[m_currentPage])
		if urlCurr ~= nil then
			self:Navigate(urlCurr)
		end
	elseif locationName == "error.html" then
		return
	--elseif string.find(webTitle, "Internet") ~= nil then
	--	if errorUrl ~= nil then
	--		self:Navigate(errorUrl)
	--	end
	end
end

function OnTitleChange(self, strtitle)
	webTitle = strtitle
end

function webMain_OnInitControl(self)
	m_currentPage = 1

	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	
	if loadingUrl == nil or errorUrl == nil then
		loadingUrl = string.format("%s%s", myClass:GetAppPath(), "\\html\\loading.html")
		errorUrl = string.format("%s%s", myClass:GetAppPath(), "\\html\\error.html")
	end
	self:Navigate(loadingUrl)
end

function menu_web_OnClick(self)
	m_currentPage = 1
	
	if loadingUrl ~= nil then
		local owner = self:GetOwner()
		local webMain = owner:GetUIObject("webMain")
		webMain:Navigate(loadingUrl)
	end
end

function menu_prev_OnClick(self)
	if m_currentPage > 1 then
		m_currentPage = m_currentPage - 1
		
		if loadingUrl ~= nil then
			local owner = self:GetOwner()
			local webMain = owner:GetUIObject("webMain")
			webMain:Navigate(loadingUrl)
		end
	end
end

function menu_next_OnClick(self)
	if m_currentPage < 5 then
		m_currentPage = m_currentPage + 1
		
		if loadingUrl ~= nil then
			local owner = self:GetOwner()
			local webMain = owner:GetUIObject("webMain")
			webMain:Navigate(loadingUrl)
		end
	end
end

function btnnav_OnClick(self)
	--打开www.tingshijie.com
	if myClass==nil then
		myClassFactory = XLGetObject("Rola.MyClass.Factory")
		myClass = myClassFactory:CreateInstance()
	end
	myClass:OpenFolder()
end

function OnNewWindow3(self, flags, urlcontext, url)
	--[[self:Navigate(url)]]--
	-- XLGetGlobal("BoltFox.UIHelper"):NavigateToUrl(url,true)
	-- return 0, self:GetRawWebBrowser(), true
end

function GetScreenPos(menuRoot, x, y)
	local left,top,right,bottom = menuRoot:GetObjPos()
	
	local width = right - left
	local height = bottom - top
	
	local menuTree = menuRoot:GetOwner()
	local menuHostWnd = menuTree:GetBindHostWnd()
	
	local sleft, stop, sright, sbottom = menuHostWnd:GetMonitorRect(x, y)
	if x + width > sright then
		x = x - width
	end
	
	if y + height > sbottom then
		y = y - height
	end
	
	return x, y, width, height
end	

function treeview_OnRButtonClicked(self,fun, x, y,item)
	local tleft,ttop,tright,tbottom = self:GetObjPos()
	x = x + tleft + 10 --10为箭头的误差
	y = y + ttop + 5
	--local attr = item:GetAttribute()
	local templateMananger = XLGetObject("Xunlei.UIEngine.TemplateManager")				
	local menuTreeTemplate = templateMananger:GetTemplate("Rola.Menu","ObjectTreeTemplate")
	local menuTree = menuTreeTemplate:CreateInstance("Rola.Menu.Instance")
	
	local hostwndManager = XLGetObject("Xunlei.UIEngine.HostWndManager")
	local parent = hostwndManager:GetHostWnd("Player.Wnd")
	local parentHandle = parent:GetWndHandle()

	local menuHostWndTemplate = templateMananger:GetTemplate("Rola.Menu", "HostWndTemplate")
	local menuHostWnd = menuHostWndTemplate:CreateInstance("Rola.Menu.Instance")
	--XLMessageBox("原 x:"..x.." y:"..y)
	menuHostWnd:BindUIObjectTree(menuTree)
	local menuContext = menuTree:GetUIObject("menu.root")
	
	x, y = parent:ClientPtToScreenPt(x,y)
	local left, top, width, height = GetScreenPos(menuContext, x, y)
	--XLMessageBox("新 x:"..x.." y:"..y)
	menuHostWnd:TrackPopupMenu(parentHandle, left, top, width, height)
	
	local objtreeManager = XLGetObject("Xunlei.UIEngine.TreeManager")	
	objtreeManager:DestroyTree("Rola.Menu.Instance")
	hostwndManager:RemoveHostWnd("Rola.Menu.Instance")
end
