 cronJob = require('cron').CronJob
 
 PATH_ACTIVITY = '/portal/media-type/html/user/h_sakaguchi_admin/page/default.psml/js_peid/P-143fe3e7fc1-10a40?action=controls.Maximize'
+PATH_TIMELINE = '/portal/media-type/html/user/h_sakaguchi_admin/page/default.psml/js_peid/P-143fe3e7fc1-10a3f?action=controls.Maximize'
 
 # {{{ SenpaiStorage
 setSenpaiStorage = (robot, key, val) ->

      @get PATH_ACTIVITY, null, (error, response, $) =>
        cacheActivities = getSenpaiStorage @robot, 'AIPO_ACTIVITIES'
        cacheActivities ||= []
        $('.auiRowTable tbody tr').each((i, elem) =>
          return if i > 5 or i is  0
          text = $(elem).text().replace /[\r\n]+/g, ','
          val = text.split(',')
          text = val[2] + ': ' + val[1]
          # a = $(elem).find('a')
          return if text in cacheActivities
          cacheActivities.push text
          @send "Aipo更新通知 #{text}"
        )
        while cacheActivities.length > 100
          cacheActivities.shift()
        setSenpaiStorage msg, 'AIPO_ACTIVITIES', cacheActivities

  send: (msg) ->
    response = new @robot.Response(@robot, {user : {id : -1, name : @room}, text : "none", done : false}, [])

module.exports = (robot) ->
  aipo = new Aipo robot, process.env.HUBOT_AIPO_SEND_ROOM, process.env.HUBOT_AIPO_BASE_URL, process.env.HUBOT_AIPO_USER, process.env.HUBOT_AIPO_PASSWORD

  checkUpdate = () ->
    getActivity()
    getTimeline()

  getActivity = () ->
#    console.log 'start getActivity!!!'
    aipo.getActivity()

  getTimeline = () ->
#    console.log 'start getTimeline!!!'
    aipo.getTimeline()

  robot.respond /aipo activity/i, (msg) ->
    getActivity()

  robot.respond /aipo timeline/i, (msg) ->
    getTimeline()

  # *(sec) *(min) *(hour) *(day) *(month) *(day of the week)
  new cronJob('*/5 * * * * *', () ->
    checkUpdate()
  ).start()

