--cnstart://10.30.11.1/video/В начале славных дел (1980)/

require('lfs')

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

local inAdr = m_simpleTV.Control.CurrentAdress
if inAdr == nil then return end

local retAdr = string.match(inAdr, '^cnstart:(//.+)' )
if not retAdr then 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

retAdr = 'file:' .. url_decode(retAdr)

local Adr = RuStr(retAdr, true)

if string.find(Adr, '   ') == nil then retAdr = Adr end

local header = string.match(retAdr, '.+/(.-)/')
if header == nil then header = retAdr end
if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle = header end

local sep = string.match (package.config, "[^\n]+")
--debug_in_file('', 'C:\\_TEMP\\cnstart_dir.txt', true)

local t, i = {}, 1
function scan_dir(path)
	for file in lfs.dir(path) do
		if file ~= "." and file ~= ".." then
			local f = path .. sep .. file
			local attr = lfs.attributes(f)
			assert(type(attr) == "table")
			if attr.mode == "directory" then 
				scan_dir(f)
			else
				local ext = string.match(file, '.+%.(.-)$')
				--debug_in_file(file .. '\n', 'C:\\_TEMP\\cnstart_dir.txt')
				local name = string.match(f, '\\(.-)\\.-%.' .. ext)
				if (ext == 'avi') or (ext == 'mkv') or (ext == 'mp4') then
					t[i]         = {}
					t[i].Id      = i
					if (name == nil) then
						name = ''
					else
						name = ' ('  .. name .. ')'
					end
					t[i].Name    = file .. name
					t[i].Adress  = 'file:' .. f
					i = i + 1
					--debug_in_file(f .. '\n', 'C:\\_TEMP\\cnstart_dir.txt')
				end
			end
		end
	end
end
local dir = string.match(retAdr, 'file:(.+)')
scan_dir(dir)
if i > 2 then
	local _, id = m_simpleTV.OSD.ShowSelect(header, 0, t, 0, 1)
	if id == nil then id = 1 end
	retAdr = t[id].Adress
else
	if t[1] ~= nil then retAdr = t[1].Adress end
end
--debug_in_file(retAdr .. '\n', 'C:\\_TEMP\\cnstart.txt')
m_simpleTV.Control.ChangeAdress = 'Yes'
m_simpleTV.Control.CurrentAdress = retAdr