-- vim:set ft=lua:
id=mg.get_var(mg.request_info.query_string,'id')

edcb.htmlEscape=15
if id then
  a=edcb.GetRecFileInfo(id)
  if a then a={a} end
else
  a=edcb.GetRecFileInfoBasic()
  table.sort(a, function(a,b) return os.time(a.startTime) > os.time(b.startTime) end)
end

ct={'<?xml version="1.0" encoding="UTF-8" ?>\r\n'}
if not a then
  table.insert(ct, '<entry><err>録画結果が存在しません</err></entry>')
else
  index=math.max(tonumber(mg.get_var(mg.request_info.query_string,'index')) or 0,0)
  count=math.max(tonumber(mg.get_var(mg.request_info.query_string,'count')) or 200,0)
  countTo=math.min(index+count,#a)

  table.insert(ct, '<entry><total>'..#a..'</total><index>'..index..'</index><count>'..math.max(countTo-index,0)..'</count><items>\r\n')
  for i=index+1,countTo do
    v=a[i]
    table.insert(ct, '<recinfo><ID>'
      ..v.id..'</ID><recFilePath>'
      ..v.recFilePath..'</recFilePath><title>'
      ..v.title..'</title><ONID>'
      ..v.onid..'</ONID><TSID>'
      ..v.tsid..'</TSID><SID>'
      ..v.sid..'</SID><eventID>'
      ..v.eid..'</eventID><service_name>'
      ..v.serviceName..'</service_name>'
      ..string.format('<startDate>%d/%02d/%02d</startDate><startTime>%02d:%02d:%02d</startTime><startDayOfWeek>',
                      v.startTime.year, v.startTime.month, v.startTime.day, v.startTime.hour, v.startTime.min, v.startTime.sec)
      ..(v.startTime.wday-1)..'</startDayOfWeek><duration>'
      ..v.durationSecond..'</duration>'
      ..string.format('<startDateEpg>%d/%02d/%02d</startDateEpg><startTimeEpg>%02d:%02d:%02d</startTimeEpg><startDayOfWeekEpg>',
                      v.startTimeEpg.year, v.startTimeEpg.month, v.startTimeEpg.day, v.startTimeEpg.hour, v.startTimeEpg.min, v.startTimeEpg.sec)
      ..(v.startTimeEpg.wday-1)..'</startDayOfWeekEpg><drops>'
      ..v.drops..'</drops><scrambles>'
      ..v.scrambles..'</scrambles><recStatus>'
      ..v.recStatus..'</recStatus><comment>'
      ..v.comment..'</comment><programInfo>'
      ..v.programInfo..'</programInfo><errInfo>'
      ..v.errInfo..'</errInfo><protect>'
      ..(v.protectFlag and 1 or 0)..'</protect></recinfo>\r\n')
  end
  table.insert(ct, '</items></entry>')
end
cl=0
for i,v in ipairs(ct) do cl=cl+#v end
dofile(mg.document_root..'\\api\\util.lua')
mg.write(Response(200, 'text/xml', 'utf-8', cl) ..'\r\n')
if mg.request_info.request_method~='HEAD' then
  for i,v in ipairs(ct) do mg.write(v) end
end
