-- vim:set ft=lua:
dofile(mg.document_root..'\\api\\util.lua')

onair=mg.get_var(mg.request_info.query_string,'onair')


edcb.htmlEscape=15
if onair then
  --放送中
  onid,tsid,sid=GetVarServiceID(mg.request_info.query_string,'id')
  key={onid=onid, tsid=tsid, sid=sid}
  utc9Now=os.time()+9*3600
  if not startTime then
    startTime=os.date('!*t',utc9Now-24*3600)
  end
  durationSecond=mg.get_var(mg.request_info.query_string,'duration') or 48*3600

  b=edcb.EnumEventInfo({key},{startTime=startTime, durationSecond=durationSecond})

  if b and #b~=0 then
    a={onid=key.onid, tsid=key.tsid, sid=key.sid, eid=0}
    a={a,a}
    table.sort(b, function(a,b) return os.time(a.startTime)<os.time(b.startTime) end)
    for j,v in ipairs(b) do
      if v.startTime then
        if utc9Now<TimeWithZone(v.startTime) then
          if j>1 then a[1]=b[j-1] end
          a[2]=v
          _startTime=TimeWithZone(v.startTime)
          endTime=a[1].durationSecond and TimeWithZone(a[1].startTime)+a[1].durationSecond or _startTime
          if endTime~=_startTime then
            if endTime<utc9Now then
              a[1]={onid=key.onid, tsid=key.tsid, sid=key.sid, eid=0, startTime=os.date('!*t',endTime), durationSecond=_startTime-endTime}
            else
              a[2]={onid=key.onid, tsid=key.tsid, sid=key.sid, eid=0, startTime=os.date('!*t',endTime), durationSecond=_startTime-endTime}
            end
          end
          break
        end
      end
    end
  end
else
  --指定番組
  onid,tsid,sid,eid=GetVarEventID(mg.request_info.query_string,'id')
  if eid>0 then
    a=edcb.SearchEpg(onid, tsid, sid, eid)
    if a then a={a} end
  else
    onid,tsid,sid,startTime=GetVarPastEventID(mg.request_info.query_string,'id')
    if startTime>0 then
      et=edcb.EnumEventInfoArchive({{onid=onid, tsid=tsid, sid=sid}}, {startTime=os.date('!*t',startTime), durationSecond=1})
      if et and #et~=0 then
        a={et[1]}
      end
    else
      --一覧
      onid,tsid,sid=GetVarServiceID(mg.request_info.query_string,'id')
      a=edcb.EnumEventInfo({{onid=onid, tsid=tsid, sid=sid}})
    end
  end
end


ct={'<?xml version="1.0" encoding="UTF-8" ?>'}
if not a or #a==0 then
  table.insert(ct, '<entry><err>EPGデータを読み込み中、または存在しません</err></entry>')
else
  basic=(tonumber(mg.get_var(mg.request_info.query_string,'basic')) or 1)~=0
  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)
  for i,v in ipairs(edcb.GetServiceList() or {}) do
    if v.onid==a[1].onid and v.tsid==a[1].tsid and v.sid==a[1].sid then
      service_name=v.service_name
      break
    end
  end
  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, '<eventinfo><ONID>'
      ..v.onid..'</ONID><TSID>'
      ..v.tsid..'</TSID><SID>'
      ..v.sid..'</SID><eventID>'
      ..v.eid..'</eventID><service_name>'
      ..(service_name or '')..'</service_name>')
    if v.startTime then
      table.insert(ct, 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>')
    end
    if v.durationSecond then
      table.insert(ct, '<duration>'..v.durationSecond..'</duration>')
    end
    if v.shortInfo then
      table.insert(ct, '<event_name>'
        ..v.shortInfo.event_name..'</event_name><event_text>'
        ..v.shortInfo.text_char..'</event_text>')
    end
    if v.contentInfoList then
      for j,w in ipairs(v.contentInfoList) do
        nibble=w.content_nibble==0x0E00 and w.user_nibble+0x6000 or
               w.content_nibble==0x0E01 and w.user_nibble+0x7000 or w.content_nibble
        table.insert(ct, '<contentInfo><nibble1>'
          ..math.floor(w.content_nibble / 256)..'</nibble1><nibble2>'
          ..(w.content_nibble % 256)..'</nibble2><component_type_name>'
          ..edcb.GetGenreName(math.floor(nibble/256)*256+255)..' - '..edcb.GetGenreName(nibble)..'</component_type_name></contentInfo>')
      end
    end
    if v.eventGroupInfo then
      for j,w in ipairs(v.eventGroupInfo.eventDataList) do
        table.insert(ct, '<groupInfo><ONID>'
          ..w.onid..'</ONID><TSID>'
          ..w.tsid..'</TSID><SID>'
          ..w.sid..'</SID><eventID>'
          ..w.eid..'</eventID></groupInfo>')
      end
    end
    table.insert(ct, '<freeCAFlag>'..(v.freeCAFlag and 1 or 0)..'</freeCAFlag>')
    if not basic then
      if v.extInfo then
        table.insert(ct, '<event_ext_text>'..v.extInfo.text_char..'</event_ext_text>')
      end
      if v.componentInfo then
        table.insert(ct, '<videoInfo><stream_content>'
          ..v.componentInfo.stream_content..'</stream_content><component_type>'
          ..v.componentInfo.component_type..'</component_type><component_tag>'
          ..v.componentInfo.component_tag..'</component_tag><text>'
          ..v.componentInfo.text_char..'</text><component_type_name>'
          ..edcb.GetComponentTypeName(v.componentInfo.stream_content*256+v.componentInfo.component_type)..'</component_type_name></videoInfo>')
      end
      if v.audioInfoList then
        for j,w in ipairs(v.audioInfoList) do
          table.insert(ct, '<audioInfo><stream_content>'
            ..w.stream_content..'</stream_content><component_type>'
            ..w.component_type..'</component_type><component_tag>'
            ..w.component_tag..'</component_tag><stream_type>'
            ..w.stream_type..'</stream_type><simulcast_group_tag>'
            ..w.simulcast_group_tag..'</simulcast_group_tag><ES_multi_lingual_flag>'
            ..(w.ES_multi_lingual_flag and 1 or 0)..'</ES_multi_lingual_flag><main_component_flag>'
            ..(w.main_component_flag and 1 or 0)..'</main_component_flag><quality_indicator>'
            ..w.quality_indicator..'</quality_indicator><sampling_rate>'
            ..w.sampling_rate..'</sampling_rate><text>'
            ..w.text_char..'</text><component_type_name>'
            ..edcb.GetComponentTypeName(w.stream_content*256+w.component_type)..'</component_type_name></audioInfo>')
        end
      end
      if v.eventRelayInfo then
        for j,w in ipairs(v.eventRelayInfo.eventDataList) do
          table.insert(ct, '<relayInfo><ONID>'
            ..w.onid..'</ONID><TSID>'
            ..w.tsid..'</TSID><SID>'
            ..w.sid..'</SID><eventID>'
            ..w.eid..'</eventID></relayInfo>')
        end
      end
    end
    table.insert(ct, '</eventinfo>\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
