/* Copyright (c) 2012-2014 LevelUP contributors
 * See list at <https://github.com/rvagg/node-levelup#contributing>
 * MIT License
 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
 */

var encodings = require('./encodings')

function getKeyEncoder (options, op) {
  var type = ((op && op.keyEncoding) || options.keyEncoding) || 'utf8'
  return encodings[type] || type
}

function getValueEncoder (options, op) {
  var type = (((op && (op.valueEncoding || op.encoding))
      || options.valueEncoding || options.encoding)) || 'utf8'
  return encodings[type] || type
}

/*
  Encode a key.
  This method takes two options, because the leveldb instance
  has options, and this operation (a put, del, or batch)
  also has options that may override the leveldb's options.
*/

function encodeKey (key, options, op) {
  return getKeyEncoder(options, op).encode(key)
}

/*
  Encode a value.
  Takes 2 options, for the same reason as encodeKey
*/

function encodeValue (value, options, op) {
  return getValueEncoder(options, op).encode(value)
}

/*
  Decode an encoded key
*/

function decodeKey (key, options) {
  return getKeyEncoder(options).decode(key)
}

/*
  Decode an encoded value
*/

function decodeValue (value, options) {
  return getValueEncoder(options).decode(value)
}

/*
  check whether this value should be requested as a buffer
  (if false, then it will be a string)
  this allows an optimization in leveldown where leveldown
  retrives a string directly, and thus avoids a memory copy.
*/

function isValueAsBuffer (options, op) {
  return getValueEncoder(options, op).buffer
}

/*
  check whether a given key should be requested as a buffer.
*/

function isKeyAsBuffer (options, op) {
  return getKeyEncoder(options, op).buffer
}


module.exports = {
    encodeKey       : encodeKey
  , encodeValue     : encodeValue
  , isValueAsBuffer : isValueAsBuffer
  , isKeyAsBuffer   : isKeyAsBuffer
  , decodeValue     : decodeValue
  , decodeKey       : decodeKey
}
