CacheUpdateStrategy = require './index'
Log = require '../../../util/log'

async = require 'async'
_ = require 'underscore'
moment = require 'moment'

class ScheduledUpdateStrategy extends CacheUpdateStrategy
  init: (callback=->)->
    @scheduleObjs = []
    for scheduleConf in @schedules
      @scheduleObjs.push(new Schedule(scheduleConf, @cache));

    async.mapSeries @scheduleObjs, 
      ((schedule, asyncCallback)-> schedule.init(asyncCallback)),
      (e)=> callback.apply(@, [])

  setConfig: (config)->
    @schedules = config.schedules;

class Schedule
  constructor: (scheduleConfig, @cache) ->
    bits = scheduleConfig['refresh_interval'].split(' ');
    @refreshInterval = moment.duration(parseInt(bits[0]), bits[1]);
    @contentTypeRegEx = @getMatcherExp(scheduleConfig['content_type']);
    @pathRegEx = @getMatcherExp(scheduleConfig['path']);

    @toBeUpdated = [];
    @timers = [];

    Log.debug "Setting up schedule for #{scheduleConfig.content_type} path 
      #{scheduleConfig.path} every #{scheduleConfig.refresh_interval}"

  getMatcherExp: (condition)->
    if condition instanceof Array
      condition = condition.join('|')
    
    if typeof condition is 'string' and condition.match /\w/
      return new RegExp(condition.replace(/\//,'\\/'),'i')

    return null

  init: (callback=->)->
    cachedRes = @cache.getAll();

    for id, resource of cachedRes
      @setSchedule(resource)

    setTimeout(
      (=> @init()), @refreshInterval.asMilliseconds()
    );

    async.mapSeries @toBeUpdated, 
      (
        (path, asyncCallback) =>
          Log.info "Scheduler updating #{path} (Overdue)";
          @cache.update(path, "Scheduled update(Overdue)", 
            asyncCallback);
      )
      (e)=> 
        @toBeUpdated = []
        callback.apply(@,[e])

  setSchedule: (resource)->
    if @contentTypeMatches(resource) and @pathMatches(resource)
      updateTimeLeft = @updateTimeLeft(resource)
      if updateTimeLeft < 0
        @toBeUpdated.push(resource.path)
        return

      Log.debug "Adding timer to update #{resource.path} after #{moment.duration(updateTimeLeft).asSeconds()} seconds"
      @timers.push(
        setTimeout( 
          (
            ()=>
              Log.info "Scheduler updating #{resource.path}";
              @cache.update resource.path, "Scheduled update"
          ), updateTimeLeft
        )
      );


  contentTypeMatches: (resource)->
    return true unless @contentTypeRegEx?
    return @contentTypeRegEx.test(resource.contentType())

  pathMatches: (resource)->
    return true unless @pathRegEx?
    return @pathRegEx.test(resource.path)

  updateTimeLeft: (resource)->
    lastUpdatedStr = resource.lastUpdated.toString().
      split(" ")[1..4].join(" ")
    lastUpdated = moment(lastUpdatedStr, 'MMM DD YYYY HH:mm:ss');
    nextUpdateTime = moment(lastUpdated).add(@refreshInterval);
    return nextUpdateTime.diff(moment());

module.exports = ScheduledUpdateStrategy;