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

if m_simpleTV.Control.ChangeAdress ~= 'No' then return end

local inAdr =  m_simpleTV.Control.CurrentAdress

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_simpleTV.Control.ChangeAdress='No'
--m_simpleTV.Control.CurrentAdress =  ' '

local session = m_simpleTV.WinInet.New("Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52")

if session == nil then return end

local rc,answer = m_simpleTV.WinInet.Get(session,inAdr)

if rc ~= 200 then return end
answer = m_simpleTV.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_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle=header end
local UserId = findpattern(inAdr,'user/(.-)/',1,5,1)
if UserId==nil then return end
--debug_in_file(UserId .. '\n')
local UserPls = 'http://gdata.youtube.com/feeds/api/users/' .. UserId .. '/playlists?alt=json&start-index=1&max-results=50'

rc,answer = m_simpleTV.WinInet.Get(session,UserPls)
m_simpleTV.WinInet.Close(session)
if rc ~= 200 then return end
answer = m_simpleTV.Common.string_fromUTF8(answer)
answer = string.gsub(answer,'$t','_t')
local tab = json.decode(answer)
--debug_in_file(answer .. '\n\n')
local retAdr =''

local i=1
local t={}
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].Adress = 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].Adress = lnk.href
			  break 
			end
			--debug_in_file('' .. lnk.href .. '\n')
		end

--debug_in_file(t[i].Name .. '\n' .. t[i].Adress .. '\n\n')
--if retAdr == '' then retAdr = t[i].Adress end

i=i+1
end

if i>1 then
     retAdr = t[1].Adress
	 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,id = m_simpleTV.OSD.ShowSelect('Select playlist',0,t,5000,1+4+8)
	if ret==1 then
	  retAdr =  t[id].Adress
	end	
 end

m_simpleTV.Control.CurrentAdress =  retAdr
dofile(m_simpleTV.MainScriptDir .. "user\\video\\youtube_user_playlists.lua")