-- НТВ+

require('jsdecode')
require('json')

 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,8000,0)
  --INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,8000,0)
-----------------------------------------------

local scr = 'var a = "0123456789abcdefghijklmnopqrstuvwxyz".split(""),b = [],c,d = a.length;for (c = 0; 24 > c; c++) b[c] = a[0 | Math.random() * d];var id =   b.join("");document.getElementById("dtext").innerHTML = id;'
local id = jsdecode.DoDecode('id',false,scr,128)

--do return end
 m_simpleTV.OSD.ShowMessage("NTV Plus : start updating" ,0xFF00,3)

local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end
 local m3u = '#EXTM3U $ExtFilter="NTV Plus"\n#EXTINF:-1,NTV Plus Web:Broadcast\nntvplusbroadcast\n'
 tfile:write(m3u)
 tfile:close() 

local url = 'http://www.ntvplus.tv/index.php?r=tv%2Fcast&sessionId=g%3A' .. id .. '&timeShift=3600'

  local rc,answer=m_simpleTV.WinInet.Get(session,url)
  m_simpleTV.WinInet.Close(session)
 if rc~=200 then
	   m_simpleTV.WinInet.Close(session)
	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
	   return
 end
answer=m_simpleTV.Common.string_fromUTF8(answer) 

answer = string.gsub( answer, 'Евроньюс','Euronews')
answer = string.gsub(answer, "\n", "")
answer = string.gsub( answer, '%[%]','%[""%]')
--debug_in_file(answer ..  '\n')
local t = json.decode(answer)
if t == nil  then
   m_simpleTV.OSD.ShowMessage("Error NTV Plus: playlist not found"  ,255,10)
   return
end

--debug_in_file(t[1].name ..  '\n')
local function CheckChannel(id)
    if id == 'channel' then
	return true
    end	
    return false
end


local i=1
local m3ustr,name,adr

while true do
  if t[i] == nil or t[i].contentType == nil then break end
 
    if CheckChannel(t[i].contentType) then
	name = 'NTV Plus Web:' .. t[i].name
	adr = t[i].videoUrl 
    end

if name == nil or adr== nil then break end

  m3ustr = '#EXTINF:-1,'  .. name ..'\n'..adr..'\n'
  tfile = io.open(tmpName,'a+')
  tfile:write(m3ustr)
  tfile:close()

  i = i + 1
end

  --опции  для загрузки плейлиста 
local p={}
p.TypeSourse = 1
p.DeleteBeforeLoad = 0
p.TypeSkip   = 1
p.TypeFind =   0
p.AutoSearch = 1
p.NumberM3U =  1
p.Find_Group = 1
p.TypeCoding = 0  --  -1-auto  0 - plane text  1- UTF8  2- unicode
p.BorpasFileFormat=0
p.ExtFilter = ''
p.AutoNumber = 0

local err,add,ref,names = m_simpleTV.Common.LoadPlayList (tmpName,p,0,true,false)
os.remove(tmpName)


  if err==true then
     local mess = "NTV Plus: channels updated (New: " .. add .. ")"
	 if add > 0 and add < 25 then 
	    names = string.gsub(names,'%$end','\n')
		mess = mess .. '\n' .. names
	 end
	 
	 m_simpleTV.OSD.ShowMessage(mess,0xFF00,3) 
  end
 
