
var db = require('mime-db')

// types[extension] = type
exports.types = Object.create(null)
// extensions[type] = [extensions]
exports.extensions = Object.create(null)

Object.keys(db).forEach(function (name) {
  var mime = db[name]
  var exts = mime.extensions
  if (!exts || !exts.length) return
  exports.extensions[name] = exts
  exts.forEach(function (ext) {
    exports.types[ext] = name
  })
})

exports.lookup = function (string) {
  if (!string || typeof string !== "string") return false
  // remove any leading paths, though we should just use path.basename
  string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  if (!string) return false
  return exports.types[string] || false
}

exports.extension = function (type) {
  if (!type || typeof type !== "string") return false
  // to do: use media-typer
  type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  if (!type) return false
  var exts = exports.extensions[type[1].toLowerCase()]
  if (!exts || !exts.length) return false
  return exts[0]
}

// type has to be an exact mime type
exports.charset = function (type) {
  var mime = db[type]
  if (mime && mime.charset) return mime.charset

  // default text/* to utf-8
  if (/^text\//.test(type)) return 'UTF-8'

  return false
}

// backwards compatibility
exports.charsets = {
  lookup: exports.charset
}

// to do: maybe use set-type module or something
exports.contentType = function (type) {
  if (!type || typeof type !== "string") return false
  if (!~type.indexOf('/')) type = exports.lookup(type)
  if (!type) return false
  if (!~type.indexOf('charset')) {
    var charset = exports.charset(type)
    if (charset) type += '; charset=' + charset.toLowerCase()
  }
  return type
}
