/*global window: false, chrome: false */

var db;

/**
 * Write data to db.
 *
 * @param {string} name Key
 * @param {mixed} value Value
 */
function save(name, value) {
  if (typeof value === 'undefined') {
    value = null;
  }

  if (value !== null && typeof value === 'object') {
    value = JSON.stringify(value);
  }

  db.setItem(name, value);
}

/**
 * Fetch data from db.
 *
 * @param {string} name Key
 */
function get(name) {
  var value = db.getItem(name);

  try {
    var o = JSON.parse(value);

    // if it's an object return the object,
    // otherwise, return the original value or string
    if (o && typeof o === 'object') {
      return o;
    }
  } catch (e) { }

  return value;
}

module.exports = function(storage) {
  db = storage;

  return {
    /**
     * Chrom local storage api.
     *
     * @link https://developer.chrome.com/extensions/storage#property-local
     */
    local: {
      /**
       * Write data to db
       *
       * @param {object} data key-value pair object
       * @param {function} callback Function to call when saving process is done.
       */
      set: function(data, callback) {
        var key;
        if (data && typeof data === 'object') {
          for (key in data) {
            save(key, data[key]);
          }
        }
        callback();
      },

      /**
       * Get data from db
       *
       * @param {string} key Key
       * @param  {function} callback Function to call when done.
       * @return {mixed} Data
       */
      get: function(key, callback) {
        var value = {}, items;
        items = get(key);
        value[key] = items;
        callback(value);
      }
    }
  };
};
