-- This is a proprietary plugin, property of Andreas Bielawski, (c) 2015 <andi (dot) b (at) outlook (dot) de>
-- DO NOT USE WITHOUT PERMISSION

do

local function get_epg(epg_time)
  if epg_time == 'jetzt' then
    url = 'https://query.yahooapis.com/v1/public/yql?q=select%20pubdate,title,link%20from%20feed%20where%20url%3D%27http%3A%2F%2Fwww.tvspielfilm.de%2Ftv-programm%2Frss%2Fjetzt.xml%27&format=json&callback='
    text = 'Jetziges TV-Programm:'
  elseif epg_time == '20:15' then
    url = 'https://query.yahooapis.com/v1/public/yql?q=select%20pubdate,title,link%20from%20feed%20where%20url%3D%27http%3A%2F%2Fwww.tvspielfilm.de%2Ftv-programm%2Frss%2Fheute2015.xml%27&format=json&callback='
	text = 'TV-Programm für 20:15:'
  end
  local res,code  = https.request(url)
  local data = json:decode(res).query.results
  if code ~= 200 then return "HTTP-Fehler" end
  if not data then return "HTTP-Fehler" end

  for n in pairs(data.item) do
    text = text..'\n'..string.sub(data.item[n].title, 9)..'\n'..data.item[n].link..'\n'
  end
  
  if epg_time == '20:15' then
    cache_data('epg', 'primetime', text, 3600, 'key')
  end

  return text
end

local function run(msg, matches)
  if matches[1] == '20:15' then
    local hash = 'telegram:cache:epg:primetime'
	if redis:exists(hash) then
	  return redis:get(hash)
	end
  end
  local epg = get_epg(matches[1])
  return epg
end

return {
  description = "TV-Programm abrufen", 
  usage = {
    "/epg 20:15: TV-Programm für 20:15",
	"/epg jetzt. Jetziges TV-Programm"
  },
  patterns = {
    "^/epg (20%:15)$",
    "^/epg (jetzt)"
  },
  run = run 
}

end