require 'json'

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

local inAdr = m_simpleTV.Control.CurrentAdress

if inAdr == nil then return end

local index = findpattern(inAdr, 'ivi%.ru/watch/(.+)', 1, 6, 0)
if index == nil then return end

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

--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 rc, answer = m_simpleTV.WinInet.Get(session, 'www.ivi.ru', index)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	return
end

function RuStr(Str, isFrom)
	if Str == nil then return end
	if isFrom == true then
		return m_simpleTV.Common.string_fromUTF8(Str, 1251)
	else
		return m_simpleTV.Common.string_toUTF8(Str, 1251)
	end
end

answer = RuStr(answer, true)

--debug_in_file(answer .. '\n', 'C:\\ivi_ru.txt', true)

local title = string.match(answer, '<title>(.-) смотреть .-</title>')
if title == nil then title = inAdr end

local videoid = string.match(index, '.+/(%d+)')
local i, a = 1, {}
local retAdr = ''
local serial = false

--http://www.ivi.ru/watch/126869
--http://www.ivi.ru/watch/sled_pirani
--http://www.ivi.ru/watch/sledstvie_po_telu/season2

--Сериал--------------------------------------------------------------------------------------------------------
if videoid == nil then
	local iviAdr
	--Несколько сезонов
	local s = findpattern(answer, '<div class="seasons%-block"(.-)</div>', 1, 0, 0)
	if s ~= nil then
		--<a href="/watch/sledstvie_po_telu/season1" itemprop="name">1</a>
		for link, num in string.gmatch(s, '<a href="(.-)" itemprop="name">(.-)</a>') do
			a[i]         = {}
			a[i].Id      = i
			a[i].Name = 'Сезон ' .. num
			a[i].Adress  = 'http://www.ivi.ru' .. link
			retAdr = a[i].Adress
			i = i + 1
		end
		if i > 2 then
			local _, id = m_simpleTV.OSD.ShowSelect(title, 0, a, 0, 1)
			if id == nil then id = 1 end
			retAdr = a[id].Adress
			title = title .. ' - ' .. a[id].Name
		end
		if retAdr == nil then
			m_simpleTV.WinInet.Close(session)
			return
		end
		rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
		if rc ~= 200 then
			m_simpleTV.WinInet.Close(session)
			return
		end
		answer = RuStr(answer, true)
		--debug_in_file(answer .. '\n', 'C:\\ivi_ru.txt', true)
	end
	--Один сезон
	s = findpattern(answer, '<ul id="season%-serie%-list"(.-)</ul>', 1, 0, 0)
	if s == nil then
		m_simpleTV.WinInet.Close(session)
		return
	end
	i, a = 1, {}
	for w in string.gmatch(s, '<li>(.-)</li>') do
		--<a href="/watch/sledstvie_po_telu/119315"
		--<meta itemprop="episodeNumber" content="1">
		local link = string.match(w, '<a href="(.-)"')
		local num = string.match(w, '<meta itemprop="episodeNumber" content="(.-)"')
		a[i]         = {}
		a[i].Id      = i
		a[i].Name = 'Серия ' .. num
		a[i].Adress  = 'http://www.ivi.ru' .. link
		retAdr = a[i].Adress
		i = i + 1
	end
	if i > 2 then
		local _, id = m_simpleTV.OSD.ShowSelect(title, 0, a, 0, 1)
		if id == nil then id = 1 end
		retAdr = a[id].Adress
        title = title .. ' ' .. a[id].Name
	end
	if retAdr == nil then
		m_simpleTV.WinInet.Close(session)
		return
	end
	videoid = string.match(retAdr, '.+/(%d+)')
	if videoid == nil then
		m_simpleTV.WinInet.Close(session)
		return
	end
end
----------------------------------------------------------------------------------------------------------------

--Фильм---------------------------------------------------------------------------------------------------------
index = 'api/json'
local url = 'api.digitalaccess.ru'
local header = 'Content-Type: application/json'
local body = '{"method":"da.content.get","params":["'.. videoid .. '",{"site":"1"}]}'

rc, answer = m_simpleTV.WinInet.Post(session, url, index, header, body)
if rc ~= 200 then
	m_simpleTV.OSD.ShowMessage("Error ivi.ru - " .. rc, 255, 10)
	m_simpleTV.WinInet.Close(session)
	return
end

answer = RuStr(answer, true)
answer = string.gsub(answer, '(%[%])', '"nil"')

--debug_in_file(answer .. '\n', 'C:\\ivi_ru.txt', true)
m_simpleTV.WinInet.Close(session)

local t = json.decode(answer)
if t == nil or t.result == nil or t.result.files == nil then
	m_simpleTV.OSD.ShowMessage("Error ivi.ru - can't decode json",255,10)
	--m_simpleTV.WinInet.Close(session)
	return
end

i, a = 1, {}
while true do
	if t.result.files[i] == nil then break end
	a[i] = {}
	a[i].Id = i
	a[i].Name = 'Качество ' .. t.result.files[i].content_format
	a[i].Adress = t.result.files[i].url
	retAdr = a[i].Adress
	i = i + 1
end
if i > 2 then
	local _, id = m_simpleTV.OSD.ShowSelect(title, 0, a, 0, 1)
	if id == nil then id = 1 end
	retAdr = a[id].Adress
	--debug_in_file(retAdr .. '\n', 'C:\\ivi_ru.txt', true)
end

if retAdr == nil then
	m_simpleTV.OSD.ShowMessage("Error ivi.ru - can't find adress",255,10)
	return
end

--[[
if  string.match( retAdr, '%.f4m$' )  then
	m_simpleTV.OSD.ShowMessage("Error ivi.ru - f4m not supported now",255,10)
	--m_simpleTV.OSD.ShowMessage(retAdr, 255, 10)
	--do return end
	do return end
	url = findpattern(retAdr,'http://(.-)/',1,0,0)
	index = retAdr:sub(url:len()+1)
	url = findpattern(retAdr,'http://(.-)/',1,7,1)

	rc,answer=m_simpleTV.WinInet.Get(session, url, index)
	m_simpleTV.WinInet.Close(session)

	if rc ~= 200 then
		m_simpleTV.OSD.ShowMessage("Error ivi.ru - can't find adress",255,10)
		return
	end

	retAdr = decode64(retAdr)
	return
end
]]
----------------------------------------------------------------------------------------------------------------

m_simpleTV.Control.CurrentTitle = title
m_simpleTV.Control.CurrentAdress = retAdr