var fd = use('internal/fd')
var wildstar = use('internal/wildstar')

function last_pos(str, sep) {
  var last = null
  replace(str, sep, function(m, pos) {
    last = pos
    return m
  })
  return last
}

// Helper to join paths
function join_paths(base, rel) {
  var b = replace(base, /\/+$/, "")
  var r = replace(rel, /^\/+/, "")
  if (!b) return r
  if (!r) return b
  return b + "/" + r
}

fd.join_paths = join_paths
fd.basename = function basename(path) {
  var last = last_pos(path, '/')
  if (last == null) return path
  return text(path, last+1)
}

fd.dirname = function dirname(path) {
  var last = last_pos(path, '/')
  if (last == null) return ""
  return text(path,0,last)
}

fd.stem = function stem(path) {
  var last = last_pos(path, '.')
  if (last == null) return path
  return text(path,0,last)
}

fd.globfs = function(globs, dir) {
  var _dir = dir
  if (_dir == null) _dir = "."
  var results = []
  
  function check_neg(path) {
    var found = false;
    arrfor(globs, function(g) {
      if (starts_with(g, "!") && wildstar.match(text(g, 1), path, wildstar.WM_WILDSTAR)) {
        found = true;
        return true;
      }
    }, null, true);
    return found;
  }
  
  function check_pos(path) {
    var found = false;
    arrfor(globs, function(g) {
      if (!starts_with(g, "!") && wildstar.match(g, path, wildstar.WM_WILDSTAR)) {
        found = true;
        return true;
      }
    }, null, true);
    return found;
  }

  function visit(curr_full, rel_prefix) {
    if (rel_prefix && check_neg(rel_prefix)) return

    var list = fd.readdir(curr_full)
    if (!list) return
    
    arrfor(list, function(item) {
      var item_rel = rel_prefix ? rel_prefix + "/" + item : item
      
      var child_full = join_paths(curr_full, item)
      var st = fd.stat(child_full)
      
      if (st.isDirectory) {
        if (!check_neg(item_rel)) {
          visit(child_full, item_rel)
        }
      } else {
        if (!check_neg(item_rel) && check_pos(item_rel)) {
          push(results, item_rel)
        }
      }
    });
  }
  
  var st = fd.stat(_dir)
  if (st && st.isDirectory) {
    visit(_dir, "")
  }
  
  return results
}

fd.ensure_dir = function ensure_dir(path) {
  if (fd.is_dir(path)) return true
  var parts = array(path, '/')
  var current = starts_with(path, '/') ? '/' : ''
  var i = 0
  for (i = 0; i < length(parts); i++) {
    if (parts[i] == '') continue
    current = current + parts[i] + '/'
    if (!fd.is_dir(current))
      fd.mkdir(current)
  }
  return true
}

fd.safe_package_path = function safe_package_path(pkg) {
  if (pkg && starts_with(pkg, '/'))
    return replace(replace(pkg, '/', '_'), '@', '_')
  return replace(pkg, '@', '_')
}

return fd
