vhost = require 'vhost'
url = require 'url'
_ = require 'underscore'
SiteCache = require '../lib/cache/sitecache'
SiteBackend = require '../lib/backend'
SiteDispatcher = require '../lib/dispatcher'
Log = require '../util/log'
conf = require '../lib/conf'

class noDelaySite
  constructor: (@domain, @config) ->
    throw new Error("Domain must be configured for noDelaySite") unless @domain?
    throw new Error("Backend must be configured for noDelaySite") unless @config.backend?
    @config = _.extend({}, noDelaySite.config, @config)

  init: (callback)->
    @initBackend()
    @initCache ()->
      @initUpdateStratagies();
      @initDispatcher()
      callback.apply @, []

  vhost: ()->
    throw new Error("Cannot create vhost without dispatcher") unless @dispatcher?
    Log.info "Added vhost for \"#{@domain}\"."
    return vhost @domain, @dispatcher.app()

  initCache: (callback)->
    throw new Error("Cannot init cache before backend") unless @backend?
    Log.debug "Initializing cache for \"#{@domain}\"."
    @cache = new SiteCache @domain, @backend
    @cache.init ()=>
      callback.apply @,[];

  initBackend: ()->
    Log.debug "Initializing backend for \"#{@domain}\"."
    @backend = new SiteBackend(@);

  initDispatcher: ()->
    throw new Error("Cannot init dispatcher before backend") unless @backend?
    throw new Error("Cannot init dispatcher before cache") unless @cache?
    Log.debug "Initializing dispatcher for \"#{@domain}\"."
    @dispatcher = new SiteDispatcher(@)
    @dispatcher.init();

  initUpdateStratagies: ()->
    for stratagy, stratagyConfig of @config.update_stratagies
      Log.info "Setting up #{stratagy} update strategy"
      UpdateStrategy = require "../lib/cache/update_strategy/#{stratagy}"
      theUpdateStrategy = new UpdateStrategy(@cache, @backend);
      theUpdateStrategy.setConfig stratagyConfig
      theUpdateStrategy.init();

  canCache: (obj)->
    unless typeof obj is "string"
      return (obj.method.toUpperCase() is 'GET' or obj.method.toUpperCase() is 'HEAD') and 
        @canCache(obj.url)

    theUrl = obj
    opts = url.parse(theUrl)
    return not 
      (@config.blacklist instanceof Array and
        opts.path in @config.blacklist)

noDelaySite.config = {}

module.exports = noDelaySite;