--input
--m_simpleTV.Control.Reason              Error|EndReached|Stopped
--m_simpleTV.Control.CurrentAdress      Address from database
--m_simpleTV.Control.RealAdress			 Real Address

--output
--m_simpleTV.Control.CurrentAdress      Address from database
--m_simpleTV.Control.Action              dodefault|repeat

local IsAd = (m_simpleTV.Control.IsAD and m_simpleTV.Control.IsAD() or false)

if false then   --  тестовый блок 
	local  text = 'events:\n'
	text = text ..'TVSCurrentSource='.. (TVSources_var.CurrentSource or '') .. '\n'
	text = text ..'CurrentTitle='.. (m_simpleTV.Control.CurrentTitle_UTF8 or 'nil') .. '\n'
	text = text ..'CurrentAdress='.. (m_simpleTV.Control.CurrentAdress or 'nil') .. '\n' 
	text = text ..'ChangeAdress=' .. (m_simpleTV.Control.ChangeAdress or 'nil') .. '\n' 
	text = text ..'Reason='.. (m_simpleTV.Control.Reason or 'nil') .. '\n'
	text = text ..'Action='.. (m_simpleTV.Control.Action or 'nil')..'\n'
	text = text ..'EventPlayingInterval='.. (m_simpleTV.Control.EventPlayingInterval or 'nil') .. '\n'
	text = text ..'EventTimeOutInterval='.. (m_simpleTV.Control.EventTimeOutInterval or 'nil') .. '\n'
	text = text ..'Peers='.. (m_simpleTV.Control.Peers or 'nil') .. '\n'
	text = text ..'Buffering='.. (m_simpleTV.Control.Buffering or 'nil') .. '\n'
	text = text ..'IsAd='.. (IsAd==true and 'true' or 'false') .. '\n'
	 
	m_simpleTV.OSD.ShowMessage_UTF8(text ,0xD7EBFA,6)
end


---(откл.)--- Проверка  на рекламу ----------------------------------------------
--if false and m_simpleTV.Control.Reason=='Playing' and IsAd==true  then
 --local value = m_simpleTV.Config.GetConfigInt(m_simpleTV.Defines.ID_TORRENTSTREAM_ALLOW_AD) or 1
 --if value==0 then
       --tvs_core.tvs_debug('Detect Ad.')
        --m_simpleTV.Control.SetTitle('Реклама')
	    --m_simpleTV.Control.SetPosition(1.0)
	    --m_simpleTV.Control.ExecuteAction(82)	    
	    --m_simpleTV.Control.EventPlayingInterval = 1000
	    --m_simpleTV.Control.EventTimeOutInterval = 0	    
	    --return
 --end	    
--end 
------------- Открыли URL или файл с диска, они нам не нужны -------------------
if  m_simpleTV.Control.CurrentTitle and m_simpleTV.Control.CurrentTitle:find('[\\/]') then return end

------------- Для IPTV - смена сервера по ctrl+m -------------------------------
 if m_simpleTV.Control.RealAdress and m_simpleTV.Control.RealAdress:find('&tvssrc=') then 
	if m_simpleTV.Control.Reason=='addressready' then
	   if not TVSources_var.tmp.MenuId  then
	      TVSources_var.tmp.MenuId = m_simpleTV.Interface.AddExtMenu_UTF8('Смена сервера','user\\TVSources\\refreshserv.lua',string.byte('M'),1)
	   end
	end
 end
 if m_simpleTV.Control.Reason=='Stopped' then
   if TVSources_var.tmp.MenuId then
      m_simpleTV.Interface.RemoveExtMenu(TVSources_var.tmp.MenuId)
      TVSources_var.tmp.MenuId=nil
   end
   return
end

 ------------ Если не наш адрес, то уходим -------------------------------------
if not m_simpleTV.Control.CurrentAdress:find('TVSources') then return end

------------- Автообновление базы -------------------------------
if TVSources_var.AutoBuild and TVSources_var.AutoBuildFL and (tvs_core.tvs_fcheck(m_simpleTV.MainScriptDir .. 'ch_base_upd.flg','yes') == 'ok') then

	tvs_core.tvs_debug('Autoupdate in watching TV. Detected the autoupdate flag. Start autoupdate...')
	tvs_core.tvs_BuildList(nil,nil)
	os.remove(m_simpleTV.MainScriptDir .. 'ch_base_upd.flg')
end


---------------------------- сохраняем удачный источник -------------------------
if (not IsAd and m_simpleTV.Control.CurrentTitle~=nil and 
    m_simpleTV.Control.Reason=='Playing' and 
    m_simpleTV.Control.EventPlayingInterval>0) then

	local CurrentTitleUTF8 = m_simpleTV.Control.CurrentTitle_UTF8   	
	local CurrentSrcUTF8 = TVSources_var.CurrentSource or ''

    if not tvs_core.isUTF8(CurrentSrcUTF8) then
       CurrentSrcUTF8 = m_simpleTV.Common.string_toUTF8(CurrentSrcUTF8)
	end
	
	local vers = m_simpleTV.Common.GetVersion() 
	if (vers >= 580 )  then       -- начиная с 581 версии устанавливаем сами, до этого выводилось значение из ShowSelect
	    local  temp = '['..CurrentSrcUTF8..'] ' .. m_simpleTV.Control.CurrentTitle_UTF8:gsub("%b[]%s+","")
	    
		m_simpleTV.Control.SetTitle(temp)
	end
         	
	TVSources_var.BadSrcCount = 0 -- обнуляем счетчик неудачных источников
	local Id,inAdr
	inAdr = string.gsub(m_simpleTV.Control.CurrentAdress,'\'','"')
	if string.match( m_simpleTV.Control.CurrentAdress, 'TVSources' ) ~=nil then
		Id = findpattern(inAdr,'id=%b""',0,4,1) or tvs_core.tvs_clearname(CurrentTitleUTF8) or ''
		
		tvs_core.tvs_SaveLastPlay (Id,TVSources_var.CurrentAdress, CurrentSrcUTF8)
		
		tvs_core.tvs_debug (Id ..'. Save last successed stream: ' .. TVSources_var.CurrentAdress.. ' CurrentSource:'.. CurrentSrcUTF8)
		m_simpleTV.Control.EventPlayingInterval = 0
		m_simpleTV.Control.EventTimeOutInterval = 0
		TVSources_var.ChangeAdress = false		

	end
	
end


-------------------------- нет сигнала в источнике -----------------------------------------------

if ( not IsAd  and 
   m_simpleTV.Control.CurrentTitle ~=nil and 
   m_simpleTV.Control.CurrentAdress:find('TVSources')  and 
   not m_simpleTV.Control.CurrentAdress:find('@SODA') and  
   (   m_simpleTV.Control.Reason == 'Stopped' or m_simpleTV.Control.Reason == 'Error' or 
       m_simpleTV.Control.Reason == 'Timeout' and m_simpleTV.Control.Buffering < 0.1  )  and 
   (   m_simpleTV.Control.Action =='dodefault' or m_simpleTV.Control.Action =='repeat') and 
   TVSources_var.NoSignal == true) then
    


	local CurrentTitleUTF8 = m_simpleTV.Control.CurrentTitle_UTF8 
	local inAdr = string.gsub(m_simpleTV.Control.CurrentAdress,'\'','"') or 'empty'
	local retAdr = TVSources_var.CurrentAdress or 'empty'
	
	local tmpName,tmpSrc,default,Id

	Id = findpattern( inAdr,'id=%b""',0,4,1) or tvs_core.tvs_clearname(CurrentTitleUTF8) or ''
	default = findpattern( inAdr,'df=%b""',0,4,1) or TVSources_var.Default or ''
	
		local rrr = m_simpleTV.Control.Reason
	    if m_simpleTV.Control.Reason == 'Timeout' then
	       rrr = rrr .. ' '..TVSources_var.ChannelWaiting ..' sec.'
		   tvs_core.tvs_debug(CurrentTitleUTF8 .. '. ID: ' .. Id .. ', No signal on URL: ' .. retAdr .. ' Reason='..rrr)
	    end   


	if Id == '' or m_simpleTV.Control.Reason == 'Stopped' then return end

	
	if TVSources_var.NextSr then
		TVSources_var.BadSrcCount = TVSources_var.BadSrcCount + 1
		
	
		tmpSrc,tmpName = tvs_core.tvs_GetUrlById (Id, default, retAdr)
		tmpSrc = tmpSrc or ''
		
				
		if tmpSrc~='stop' then
		    if tmpName==nil then return end
			CurrentSrcUTF8 =  tmpSrc  
			
			tvs_core.tvs_debug(CurrentTitleUTF8 .. '. ID: ' .. Id .. '. Source: ' .. CurrentSrcUTF8 .. ', Start play URL: ' .. tmpName)
			tvs_core.tvs_ShowError(CurrentTitleUTF8 .. ' ['.. CurrentSrcUTF8 .. ']',0xffffff) 

			TVSources_var.CurrentAdress = tmpName
			TVSources_var.CurrentSource = tmpSrc
			m_simpleTV.Control.CurrentAdress = tmpName
			TVSources_var.ChangeAdress = true
			m_simpleTV.Control.Action = 'repeat'
            --m_simpleTV.Control.Reason = 'addressready'
            --m_simpleTV.Control.ExecuteAction(63)
		else
			m_simpleTV.Control.Action = 'stop'
			m_simpleTV.Control.ExecuteAction(11)  -- 11   Stop (KEYSTOP)
		end
	else
		dofile (m_simpleTV.MainScriptDir .. 'user/TVSources/selectsource.lua')
	end
end
