fs = require 'fs'
path = require 'path'

Instance = ->
#  cache for templates, express 3.x doesn't do this for us
  @cache = {};
  @__express = middleware.bind(@)
  return


middleware = (filename, options, cb) ->
  cache = @cache


#  render the original file
  render_file = (locals, cb) ->
    template = cache[filename]
    return cb(null, template) if template?

    fs.readFile filename, 'utf8', (err, str) ->
      return cb(err) if err?
      final_str = env_block(str, options.settings.env)
      final_str = js_replace(final_str)
      final_str = css_replace(final_str)
      cache[filename] = final_str if options.cache
      cb(null, final_str)

  render_file(options, cb)

js_replace= (str) ->
  sub(str, /{{{js\s(.*)}}}/g, 'js')

css_replace= (str) ->
  sub(str, /{{{css\s(.*)}}}/g, 'css')

env_block= (str, env) ->
  patt = /\{env\s(.*)\}((?:.|\n)*)?\{\/env\}/
  final_str = str
  matches = str.match(patt)
  if matches?
    if env == matches[1]
      final_str = final_str.replace(matches[0], matches[2])
    else
      final_str = final_str.replace(matches[0], '')
  final_str 

sub = (str, patt, type) ->
  final_str = str
  matches = str.match(patt)
  if matches?
    for matched in matches
      final_str = final_str.replace(matched, eval(type) matched.split("{{{#{type} ")[1].split('}}}')[0].trim())
  
  final_str


module.exports = new Instance()
module.exports.create = ->
  new Instance()
