--script for youtube playlists (12/03/2014)
-- open link http://www.youtube.com/user/Fletcher2008/playlists
require('json')

if m_LinkToPlay.Control.ChangeAddress ~= 'No' then return end

local inAdr = m_LinkToPlay.Control.CurrentAddress

if inAdr == nil then return end
inAdr = string.gsub(inAdr, 'https', 'http')
if not string.match(inAdr, '^http://www%.youtube%.com/user/(.+)/playlists$') then return end

m_LinkToPlay.Control.ChangeAddress = 'Yes'
m_LinkToPlay.Control.CurrentAddress = ''

local session = m_LinkToPlay.WinInet.New("Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52")
if session == nil then return end

--debug_in_file(inAdr .. '\n', nil, true)

local rc, answer = m_LinkToPlay.WinInet.Get(session, inAdr)
if rc ~= 200 then return end

--debug_in_file(answer .. '\n', nil, true)
answer = m_LinkToPlay.Common.string_fromUTF8(answer)

local header =  findpattern( answer,'<title>(.-)</title>',1,7,8)
if header==nil then header=inAdr end
header = string.gsub(header,'&quot;','"')
header = string.gsub(header,'&raquo;','')
header = string.gsub(header,'&#39;',"'")
header = string.gsub(header,'&amp;',"&")

if m_LinkToPlay.Control.CurrentTitle ~= nil then m_LinkToPlay.Control.CurrentTitle = header end

local UserId = findpattern(inAdr, 'user/(.-)/', 1, 5, 1)
if UserId == nil then return end
local UserPls = 'http://gdata.youtube.com/feeds/api/users/' .. UserId .. '/playlists?alt=json&start-index=1&max-results=50'

rc, answer = m_LinkToPlay.WinInet.Get(session, UserPls)
m_LinkToPlay.WinInet.Close(session)

--debug_in_file(answer .. '\n', nil, true)
if rc ~= 200 then return end

answer = m_LinkToPlay.Common.string_fromUTF8(answer)
answer = string.gsub(answer,'$t','_t')

local tab = json.decode(answer)
--debug_in_file(answer .. '\n\n', nil, true)
local retAdr =''

local i, t = 1, {}
while true do
	if tab.feed.entry[i] == nil then break end
	t[i]        = {}
	t[i].Id     = i
	t[i].Name   = i .. '. ' .. tab.feed.entry[i].title._t
	t[i].Address = tab.feed.entry[i].link[1].href
	for w, lnk in pairs(tab.feed.entry[i].link) do
		if string.match(lnk.href, '^http://www%.youtube%.com/playlist') then
			t[i].Address = lnk.href
			break
		end
	end
	--debug_in_file(t[i].Name .. '\n' .. t[i].Address .. '\n\n')
	--if retAdr == '' then retAdr = t[i].Address end
	i = i + 1
end

if i > 1 then
	retAdr = t[1].Address
	if retAdr == nil then
		--m_simpleTV.OSD.ShowMessage("Youtube Error - can't find playlist",255,10)
		retAdr = ''
		return
	end
end

if i > 2 then
	local ret = m_LinkToPlay.Taskbar.AddList(header, 0, t, 5000, 0)
	return
	--if ret==1 then retAdr =  t[id].Address end
end
m_LinkToPlay.Control.PlayAddress(retAdr)