require 'luaxml'


local t ={}
  t[1] = {Id=1, Name='Качество "Low" | 3 кб/с '} 
  t[2] = {Id=2, Name='Качество "Medium" | 5 кб/с '}   
  t[3] = {Id=3, Name='Качество "Hi" | 8 кб/с '} 
  
local _, select_id = m_simpleTV.OSD.ShowSelect('Выберите качество:',2,t,4000,1+4+8+64)

if not select_id or select_id==0 then return end

m_simpleTV.OSD.ShowMessage('quality : '..select_id,0xFFFF00,5)


local ExtFilter = 'PCradio'
local UpdateID  = 'PCRADIO01'
 
local url =  "http://pcradio.biz/player/listradio/pcradio_ru.xml"  

 local session=m_simpleTV.WinInet.New("Opera/12.54 (Windows NT 6.1; RU; 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,6000,0)
 local rc, data =  m_simpleTV.WinInet.Get(session,url) 
 m_simpleTV.WinInet.Close(session) 

if rc~=200 then
	m_simpleTV.OSD.ShowMessage(' Net error:'.. rc, 0x00ffff,5) 
	return 
end	
if not data then 
  	 m_simpleTV.OSD.ShowMessage('Error data.',0xFF00,5)
	return 
end
m_simpleTV.OSD.ShowMessage('get from internet ok.. ',0xFFFF00,5)

-------------- обработка xml ------------------------------

local xtable = xml.eval(data)

local text = ''
local id, name
local tcountry, tgenre, tchannel = {}, {} , {}

if type(xtable)=='table' then
	local node,nodename
	for i=1,#xtable  do
	  local xnode = xtable[i]
	  -- пропускаем Страны --
	  if false and type(xnode)=='table' and xnode[0] == 'countries' then
	      for j=1,#xnode  do
	       local t = xnode[j]
	       if t[0] == 'country' and t[1][1] and t[2][1] then	
	            id , name = t[1][1], t[2][1]           
	            --text = text .. id  .. ' ' .. name  ..'\n' 
	            tcountry[id] = name
           end
	      end    
	  end	
	  -- Стили --
	  if type(xnode)=='table' and xnode[0] == 'genres' then
	      for j=1,#xnode  do
	       local t = xnode[j]
	       if t[0] == 'genre' and t[1][1] and t[2][1] then	
	            id , name = t[1][1], t[2][1]           
	            --text = text .. id  .. ' ' .. name  ..'\n' 
	            tgenre[id] = name
           end
	      end    
	  end	
	  -- Каналы --
	  if type(xnode)=='table' and xnode[0] == 'channels' then
	      for j=1,#xnode  do
	       local t = xnode[j]
	       if type(t) == 'table' and t[0] == 'channel' then			            
	            tchannel[j] = {} 
	            for k=1,#t do
	              if t[k][0] and t[k][1] then
	                name , value = t[k][0], t[k][1]
	                --text = text .. j.. ' '..k..' : ' .. name .. ' = ' .. value ..'\n' 

	                tchannel[j][name] = value:gsub(',',' ')
	              end  
	            end         		            
           end
	      end    
	  end		  
	----------  	  
	end
end


-------------- вывод в m3u ------------------------------

local out_m3u = '#EXTM3U $ExtFilter="'..ExtFilter..'" $BorpasFileFormat="1"\n'

local url, u, group
for _,v in pairs(tchannel) do

	if select_id==1 then 
	   url = v.url_low or url_med or url_hi
	  elseif select_id==2 then
	   url = v.url_med or url_low or url_hi 
	  else
	   url = v.url_hi or url_med or url_low 
	end
 
 --group = v.genre_sait or 'Разное'
 group = tgenre[ v.genre_id or '0' ]
 group = group:gsub(',',' ') -- запятых не должно быть в группах
 if v.genre_id~='29' then -- убираем тесты
 
 		 ------------- тут можно сгруппировать по-своему ----
	     group = m_simpleTV.Common.string_fromUTF8(group,1251)
		 if group:find('Разговор') or group:find('общество') then group = 'Новости Разговорное' end
		 if group:find('Религи')  then group = 'Религия' end
		 if group:find('Релакс') or group:find('Медитац') or group:find('Relax')  then group = 'Релакс Медитация' end
		 if group:find('Country')  then group = 'Кантри' end
		 if group:find('Рэгг')  then group = 'Рэггей' end
		 if group:find('Анекдот')  then group = 'Юмор' end
		 if group:find('Дабстеп')  then group = 'Электронная' end
		 if group:find('Джаз') or group:find('Блюз') then group = 'Джаз Блюз' end
	 	 group = m_simpleTV.Common.string_toUTF8(group,1251)
		 -----------------------------------------------------
		 
	 if v.title and url then
	    img = v.img:match('.+/(.+)$') or ''
	    img = '..\\Channel\\logo\\RadioAddonLogo\\PCradio\\' ..img
	    
		out_m3u = out_m3u ..'#EXTINF:-1 skipepg="1" group-title="'..group..'" tvg-logo="' .. img .. '"'	
		out_m3u = out_m3u ..' update-code="' .. UpdateID ..group..v.title .. '",' .. v.title..'\n'.. url ..'$OPT:http-user-agent=pcradio' ..'\n'
	 end 
 end	 
end

----------------------------
--local _file = m_simpleTV.MainScriptDir .. 'user\\Radio\\temp.m3u'
--debug_in_file(out_m3u, _file, true)
--if true then return end	
--os.remove(_file)
-------------------------

 local tmpName = m_simpleTV.Common.GetTmpName()
  if tmpName==nil then 
  	 m_simpleTV.OSD.ShowMessage('Error get tmp filename.',0xFF00,5)
     return 
 end 
 local tfile = io.open(tmpName,'w+')
 if tfile==nil then 
	os.remove(tmpName)
	 m_simpleTV.OSD.ShowMessage('Error open tmp file : '..tmpName,0xFF00,5)
	return
 end
  
 tfile:write(out_m3u)
 tfile:close() 

m_simpleTV.OSD.ShowMessage('base update.. ',0xFFFF00,5)

local p={}
p.TypeSourse = 1
p.DeleteBeforeLoad = 0
p.TypeSkip   = 1
p.TypeFind =   0
p.AutoSearch = 1
p.NumberM3U =  0
p.Find_Group = 1
p.TypeCoding = 1  --    -1 - auto,  0 - plane text,  1 - UTF8,  2 - unicode
p.BorpasFileFormat=1
p.ExtFilter = ExtFilter
p.AutoNumber = 0
p.UpdateID = UpdateID 
p.NotDeleteWhenRefresh = 0

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

if err==true then
     local mess = "PCradio - радиостанции обновлены (" .. 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,5)
	 
end
