fs = require("fs")
path = require("path")
ETag = require('etag')

# 递归深度执行代码
# deepFunc: 单项值、回调
# cumulateFunc: 单项结果，单项值、deep
_deepDo = (list, deepFunc, cumulateFunc, callback, deep)->
  deep = deep or 0
  if not list[deep]
    callback() if callback
    return
  deepFunc list[deep], (result)->
    if cumulateFunc
      cumulateFunc(result, list[deep], deep)
    # 递归
    if deep + 1 < list.length
      _deepDo(list, deepFunc, cumulateFunc, callback, deep + 1)
    else
      callback() if callback

opts = {}
combo = (req, res)->
  assetsPath = opts.assets_path or "./"
  COMBO_TAG = opts.combo_tag or "??"
  COMBO_DIR_TAG = opts.combo_dir_tag or "__"
  COMBO_MOD_SPLIT = opts.combo_mod_split or ","
  DEBUG_TAG = opts.debug_tag or 'debug'
  DEBUG_PREFIX = opts.debug_prefix or 'debug.'
  isDebug = false
  url = req.url
  fileList = []
  fileExt = null
  fileSize = 0
  fileLastModifyed = null
  fileLastModifyedStat = null
  try
    # 计算处理的文件队列
    addToList = (file)->
      if fs.existsSync(file) and fs.statSync(file).isFile()
        stat = fs.statSync(file)
        if stat.isFile()
          ext = path.extname(file)
          if not fileExt or fileExt is ext
            # 文件类型
            fileExt = ext
            # 文件大小
            fileSize += stat.size
            # 最后修改时间
            if not fileLastModifyed or stat.mtime > fileLastModifyed
              fileLastModifyed = stat.mtime
              fileLastModifyedStat = stat
            fileList.push(file)

    # 处理url
    url = path.normalize url.replace(/\.\./g, '')
    comboIndex = url.indexOf(COMBO_TAG)
    # 模块combo的处理判断
    if comboIndex > -1
      _resArr = url.slice(comboIndex + COMBO_TAG.length).split(COMBO_DIR_TAG)
      fileDir = if _resArr.length > 1 then _resArr.shift() else ''
      comboFiles = _resArr.shift().split(COMBO_MOD_SPLIT)
      isDebug = !!(_resArr.length && _resArr.shift().indexOf(DEBUG_TAG) != -1)
      for file in comboFiles
        if isDebug
          _file = file.split('/')
          _name = DEBUG_PREFIX + _file.pop()
          file = _file.concat([_name]).join('/')
        _filePath = path.join(assetsPath, fileDir, file)
        addToList(_filePath)
    else
      # no combo
      addToList path.join(assetsPath, url)
    # 请求的返回
    if fileList.length > 0
      res.type(fileExt)
      res.set({
        'Cache-Control': 'public, max-age=31536000'
        'Last-Modified': fileLastModifyed
        'Content-Length': fileSize
        'ETag': ETag(fileLastModifyedStat)
      })
      # console.log(fileList)
      _deepDo(
        fileList
        (p, cb)->
          Stream = fs.createReadStream(p,{encoding:'utf8'})
          Stream.pipe res,{end: false}
          # Stream.on 'data',(data)->
          #     console.log data
          Stream.on 'end',->
            cb()
        ->
        ->
          res.end()
      )

    # else if fileList.length is 1
    #     Stream = fs.createReadStream(fileList[0],{encoding:'utf8'})
    #     res.sendFile Stream, {maxAge: Infinity}
    else
      res.sendStatus 404
  catch e
    res.sendStatus 404
module.exports = (o)->
  opts = o
  return combo
