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

function recSetting(r,post)
  local presetID=GetVarInt(post,'presetID',0,65534)
  if presetID then
    r.recSetting=nil
    for i,v in ipairs(edcb.EnumRecPresetInfo()) do
      if v.id==presetID then
        r.recSetting=v.recSetting
        break
      end
    end
  end
  r.recSetting=getRecSetting(r.recSetting, post)
  if r.recSetting then
    return r
  end
  return false
end

function eventInfo(r)
  eventInfo=edcb.SearchEpg(r.onid, r.tsid, r.sid, r.eid)
  if eventInfo and eventInfo.startTime and eventInfo.durationSecond then
    r.title=eventInfo.shortInfo and eventInfo.shortInfo.event_name or ''
    r.startTime=eventInfo.startTime
    r.startTimeEpg=eventInfo.startTime
    r.durationSecond=eventInfo.durationSecond
    r.stationName=''
    for i,v in ipairs(edcb.GetServiceList() or {}) do
      if v.onid==r.onid and v.tsid==r.tsid and v.sid==r.sid then
        r.stationName=v.service_name
        break
      end
    end
    return r
  end
  return false
end

post=AssertPost()

id=GetVarInt(mg.request_info.query_string,'id') or 0
add=mg.get_var(post,'add')
change=mg.get_var(post,'change')
del=mg.get_var(post,'del')
OneClick=GetVarInt(mg.request_info.query_string,'oneclick',0,1)==1
toggle=GetVarInt(mg.request_info.query_string,'toggle',0,1)==1

if post then
  if add then
    onid=GetVarInt(post, 'onid') or 0
    tsid=GetVarInt(post, 'tsid') or 0
    sid=GetVarInt(post, 'sid') or 0
    eid=GetVarInt(post, 'eid') or 0
    r=recSetting({onid=onid,tsid=tsid,sid=sid,eid=eid},post)
    if r then
      r=eventInfo(r)
      if r then
        done=edcb.AddReserveData(r)
      else
        err='イベント情報が見つかりません'
      end
 	else
      err='録画設定が正しくありません'
 	end
  elseif change then
    r=edcb.GetReserveData(id)
    if r then
      if mg.get_var(post,'startdate') then
        startdate={string.match(mg.get_var(post,'startdate'), '^(%d+)%-(%d+)%-(%d+)$')}
        startTime={string.match(mg.get_var(post,'starttime'), '^(%d+):(%d+):(%d+)$')}
        r.startTime={
          year=startdate[1],
          month=startdate[2],
          day=startdate[3],
          hour=startTime[1],
          min=startTime[2],
          sec=startTime[3]
        }
        endHour,endMin,endSec=string.match(mg.get_var(post,'endtime'), '^(%d+):(%d+):(%d+)$')
        --正当な日時か検査
        if r.startTime.year and r.startTime.month and r.startTime.day and
           r.startTime.hour and r.startTime.min and r.startTime.sec and
           os.time(r.startTime) and endHour and endMin and endSec
        then
          --プログラム予約化
          r.eid=65535
          r.durationSecond=(endHour-r.startTime.hour)*3600+(endMin-r.startTime.min)*60+endSec-r.startTime.sec
          r.durationSecond=r.durationSecond+(r.durationSecond<0 and 24*3600 or 0)
          done=edcb.ChgReserveData(r)
        else
          err='不正な日時です'
        end
      else
        r=recSetting(r,post)
        if r then
          done=edcb.ChgReserveData(r)
        else
          err='録画設定が正しくありません'
        end
      end
    else
      err='予約が見つかりません'
    end
  elseif del then
    if edcb.GetReserveData(id) then
      edcb.DelReserveData(id)
      messege='<success>予約を削除しました</success>'
    else
      err='予約が見つかりません'
    end
  end
elseif OneClick then
  AssertCsrf(mg.request_info.query_string)
  onid=GetVarInt(mg.request_info.query_string,'onid') or 0
  tsid=GetVarInt(mg.request_info.query_string,'tsid') or 0
  sid=GetVarInt(mg.request_info.query_string,'sid') or 0
  eid=GetVarInt(mg.request_info.query_string,'eid') or 0
  r={onid=onid,tsid=tsid,sid=sid,eid=eid}
  for i,v in ipairs(edcb.EnumRecPresetInfo()) do
    if v.id==0 then
      r.recSetting=v.recSetting
      break
    end
  end
  r=eventInfo(r)
  if r then
    done=edcb.AddReserveData(r)
  else
    err='イベント情報が見つかりません'
  end
elseif toggle then
  AssertCsrf(mg.request_info.query_string)
  r=edcb.GetReserveData(id)
  if r then
    for i,v in ipairs(edcb.EnumRecPresetInfo()) do
      if v.id==0 then
        recMode=(v.recSetting.recMode==5 and 0 or v.recSetting.recMode)
        break
      end
    end
    r.recSetting.recMode=(r.recSetting.recMode==5 and recMode or 5)
    done=edcb.ChgReserveData(r)
  else
    err='予約が見つかりません'
  end
end

if done then
  edcb.htmlEscape=15
  if add or OneClick then
    for i,v in ipairs(edcb.GetReserveData()) do
      if v.onid==onid and v.tsid==tsid and v.sid==sid and v.eid==eid then
        id=v.reserveID
        break
      end
    end
  end
  r=edcb.GetReserveData(id)
  rsdef=edcb.GetReserveData(0x7FFFFFFF)

  messege='<success>予約を'..((add or OneClick) and '追加' or '変更')..'しました</success>'
    ..'<reserveinfo><ID>'
    ..r.reserveID..'</ID><title>'
    ..r.title..'</title><startDate>'
    ..string.format('%d/%02d/%02d</startDate><startTime>%02d:%02d:%02d</startTime><startDayOfWeek>',
                    r.startTime.year, r.startTime.month, r.startTime.day, r.startTime.hour, r.startTime.min, r.startTime.sec)
    ..(r.startTime.wday-1)..'</startDayOfWeek><duration>'
    ..r.durationSecond..'</duration><service_name>'
    ..r.stationName..'</service_name><ONID>'
    ..r.onid..'</ONID><TSID>'
    ..r.tsid..'</TSID><SID>'
    ..r.sid..'</SID><eventID>'
    ..r.eid..'</eventID><comment>'
    ..r.comment..'</comment><overlapMode>'
    ..r.overlapMode..'</overlapMode>'
    ..xmlRecSetting(r.recSetting, rsdef)
    ..'<recFileNameList>'
  for j,w in ipairs(r.recFileNameList) do
    messege=messege..'<name>'..w..'</name>'
  end
  messege=messege..'</recFileNameList></reserveinfo>\r\n'
elseif err then
  messege='<err>予約を'..(
        (add or OneClick)  and '追加'
     or (change or toggle) and '変更'
                            or '削除')
    ..'できませんでした</err><err>'..err..'</err>'
end


ct='<?xml version="1.0" encoding="UTF-8" ?><entry>'..(messege or '<err>不正値入力</err>')..'</entry>'
mg.write(Response(200, 'text/xml', 'utf-8', #ct) ..'\r\n')
if mg.request_info.request_method~='HEAD' then
  mg.write(ct)
end
