local base = _G

module ('vkcore')

function vk_getadress(inAdr)
	if inAdr == nil then return nil end
	local qualite = {'360', '480', '720'}
	local qnum = 3 --1 for 360, 2 for 480, 3 for 720
	local session = base.m_LinkToPlay.WinInet.New("Opera/9.80 (Windows NT 6.0; U; ru) Presto/2.10.229 Version/11.64")
	if session == nil then return nil end
	--INTERNET_OPTION_CONNECT_TIMEOUT
	base.m_LinkToPlay.WinInet.SetOptionInt(session, 2, 3000, 0)
	--INTERNET_OPTION_RECEIVE_TIMEOUT
	base.m_LinkToPlay.WinInet.SetOptionInt(session, 6, 5000, 0)
	local url, index
	inAdr = base.string.gsub(inAdr, '&amp;', '&')
	--base.debug_in_file(inAdr .. "\n\n\n")
	if base.string.match(inAdr, 'http://vkontakte%.') then
		url   = 'vkontakte.ru'
		index = base.findpattern(inAdr, 'vkontakte%.ru/(.*)', 1, 13, 0)
	else
		do
			url   = 'vk.com'
			index = base.findpattern(inAdr, 'vk%.com/(.*)', 1, 7, 0)
		end
	end
	if index == nil then return nil end
    --base.debug_in_file('4 - ' .. index .. "\n\n\n")
	local rc, answer = base.m_LinkToPlay.WinInet.Get(session, url, index)
	base.m_LinkToPlay.WinInet.Close(session)
	if rc ~= 200 then return nil end
	--base.debug_in_file('1)' .. answer .. "\n\n\n", nil, true)
	local qstr = base.findpattern(inAdr, '&hd=(%d+)', 1, 4, 0)
	if qstr == nil then qnum = 1 end
	if qstr ~= nil then
		qnum = base.tonumber(qstr)
		if qnum == nil or qnum > 3 then qnum = 1 end
	end
	local host = base.findpattern(answer, 'host=(.-)&amp', 1, 5, 4)
	local uid = base.findpattern(answer, 'uid=(.-)&amp', 1, 4, 4)
	local vtag = base.findpattern(answer, 'vtag=(.-)&amp', 1, 5, 4)
    local vkid = base.findpattern(answer, 'vkid=(.-)&amp', 1, 5, 4)
    local retAdr
	--base.debug_in_file('1)' .. answer .. "\n\n\n", nil, true)
	if host == nil or vtag == nil then return end
    if base.string.find(host, 'vkadre%.ru') ~= nil then
      --http://video436.vkadre.ru/assets/video/1e9270b85d58-76753232.vk.flv
      if vkid == nil then return end
      retAdr = 'http://' .. host .. '/assets/video/' .. vtag .. vkid .. '.vk.flv'
      --base.debug_in_file('5 - ' .. retAdr .. "\n\n\n")
    else
     if uid == nil then return end
     retAdr = host .. 'u' .. uid .. '/videos/' .. vtag .. '.' .. qualite[qnum] .. '.mp4'
    end
    --base.debug_in_file('5 - ' .. retAdr .. "\n\n\n")
	return retAdr
end