--script for Zvif TV 11.02.2015

require('json')

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

local inAdr =  m_simpleTV.Control.CurrentAdress

if inAdr==nil then return end

if  not string.match( inAdr, 'zvif' ) then return end

m_simpleTV.Control.ChangeAdress='Yes'
m_simpleTV.Control.CurrentAdress = ''
m_simpleTV.Control.CurrentTitle = inAdr
----------------------------------------------------------------
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

 --INTERNET_OPTION_CONNECT_TIMEOUT
 m_simpleTV.WinInet.SetOptionInt(session,2,3000,0)
 --INTERNET_OPTION_RECEIVE_TIMEOUT
 m_simpleTV.WinInet.SetOptionInt(session,6,5000,0)
---------------------------------------------------------------
local function GetRealAddress(retAdr)

   if string.match(retAdr,'youtube') then
	m_simpleTV.Control.ChangeAdress='No'
 	m_simpleTV.Control.CurrentAdress = retAdr
 	dofile(m_simpleTV.MainScriptDir .. "user\\video\\video.lua") 
   	m_simpleTV.Control.ChangeAdress='Yes'
   	retAdr = m_simpleTV.Control.CurrentAdress
   	m_simpleTV.Control.CurrentAdress=''
    end
   return  retAdr
end

local function shuffleTable(t)
	--assert(t, "table.shuffle() expected a table, got nil")
	local iterations = #t
	local j
	for i = iterations, 2, -1 do
		j = math.random(i)
		t[i], t[j] = t[j], t[i]
	end
end
---------------------------------------------------------------------------

local pls = 'http://zvif.ucoz.com/belomor.txt?rand=' .. math.random()

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

if rc~=200 then
       m_simpleTV.WinInet.Close(session)
	   return
end

answer = m_simpleTV.Common.string_fromUTF8(answer)

--debug_in_file(answer .. "\n\n")
local t = json.decode(answer)

if t == nil or t.playlist==nil then
   m_simpleTV.OSD.ShowMessage("Error - playlist not found"  ,255,10)
   return
end

local tab={}
local i=1
local retAdr = ''

while true do
  if t.playlist[i] == nil then break end
  
  tab[i] = {}
  tab[i].Id   =  i
  tab[i].Name =  t.playlist[i].comment
  tab[i].Adress  = t.playlist[i].file  
--debug_in_file(tab[i].Adress .. '\n')
  i = i+1

end

shuffleTable(tab)

   if i>1 then
        if retAdr == '' then retAdr = GetRealAddress(tab[1].Adress) end
        local title = m_simpleTV.Common.string_toUTF8(tab[1].Name)
        if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.SetTitle(title) end
  end
  if retAdr == nil then retAdr = '' end

if i>2 then
    m_simpleTV.OSD.ShowSelect('Select video',0,tab,0,32)
end

m_simpleTV.Control.CurrentAdress = retAdr



