compressible = require 'compressible'
_ = require 'underscore'

class Resource
  constructor: (options) ->
    {@content, @headers, @isBinary, @lastUpdated, @path, @status} = options;
    
    if(@isBinary)
      @content = new Buffer(@content, 'base64')
    else
      @content = new Buffer(@content,'utf-8')

  contentType: ()->
    return @header('content-type');
    
  dispatchTo: (req, res)->
    if(Resource.header(req, 'If-None-Match') is @header('ETag'))
      res.writeHead 304, 'content-length':0;
      res.end()
    else
      res.writeHead @status, @headers
      res.end(@content);


  writeHeaders: (req, res)->
    if(Resource.header(req, 'If-None-Match') is @header('If-None-Match'))
      res.writeHead 304;
    else
      res.writeHead cachedResource.status, cachedResource.getHeaders()
    res.end();

  header: (name)->
    Resource.header(@, name)

  getHeaders: ()->
    return _.extend @headers,
      via: 'X-noDelay', 'last-updated': @lastUpdated

  updateHostname: (oldHost)->
    return if @isBinary
    replaceRegEx = new RegExp("(http:)\/\/#{oldHost}/", 'gi');
    @content = new Buffer(@content.toString().replace(replaceRegEx, '/'))
    @headers = JSON.parse(JSON.stringify(@headers).replace(replaceRegEx, '/'));

Resource.fromServerResponse = (res, callback)->
  # return callback(null) unless(res.statusCode.toString() is "200");

  isBinary = Resource.isBinary(res)
  
  res.setEncoding('base64') if isBinary

  content = ""

  res.on 'data', (chunk)-> content += chunk;
  
  res.on 'end', ()->
    callback(
      new Resource 
        content: content
        headers: res.headers
        isBinary: isBinary
        lastUpdated: (new Date).toString()
        path: res.req.path
        status: res.statusCode.toString()
    );

Resource.isBinary = (response)->
  contentTypeHeader = _.find _.keys(response.headers), (key)->
    /content-type/i.test(key)
  return not compressible(response.headers[contentTypeHeader])

Resource.header = (resource, name)->
  key = _.find _.keys(resource.headers), (key)->
    (new RegExp(name,'i')).test(key)
  return null unless key?
  return resource.headers[key]

Resource.setHeader = (resource, name, value)->
  key = _.find _.keys(resource.headers), (key)->
    (new RegExp(name,'i')).test(key)
  resource.headers[key] = value

module.exports = Resource;