-- vim:set ft=lua:
dofile(mg.script_name:gsub('[^\\/]*$','')..'util.lua')

id=mg.get_var(mg.request_info.query_string,'id')
json=GetVarInt(mg.request_info.query_string,'json',0,1)==1

edcb.htmlEscape=json and 0 or 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

if json then
  if a then
    if id then
      ResponseJson(a[1])
    else
      ResponseJson(a,mg.request_info.query_string)
    end
  else
    ResponseJson({err='録画結果が存在しません'})
  end
else
  ct=CreateContentBuilder()
  ct:Append('<?xml version="1.0" encoding="UTF-8" ?>\r\n')
  if not a then
    ct:Append('<entry><err>録画結果が存在しません</err></entry>')
  else
    index=GetVarInt(mg.request_info.query_string,'index',0) or 0
    count=GetVarInt(mg.request_info.query_string,'count',0) or 200
    countTo=math.min(index+count,#a)

    ct:Append('<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]
      ct:Append('<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
    ct:Append('</items></entry>')
  end
  ct:Finish()
  mg.write(ct:Pop(Response(200,'text/xml','utf-8',ct.len)..'\r\n'))
end
