/* jshint eqnull:true browser:true  */
/* global _ */

//
// Twitch expiring cache interface
//
// Twitch.cache.write('foo', 'bar', { milliseconds: 1000 })
// setTimeout(function() { console.log(Twitch.cache.read('foo')) }, 500) // -> "bar"
// setTimeout(function() { console.log(Twitch.cache.read('foo')) }, 1500) // -> null
//
// Depends on twitch.core.js and twitch.storage.js and underscore

(function(Twitch, $) {

  var cache = {};

  cache.write = function(name, resource, options) {
    options = options || {};
    var name = 'TwitchCache:' + name;
    Twitch.storage.setObject(name, {
      resource: resource,
      expiration: options.milliseconds,
      time: new Date().getTime(),
      version: options.version,
      restrict: options.restrict
    }, _.pick(options, 'storage'));
  };

  cache.read = function(name, options) {
    options = options || {};
    var name = 'TwitchCache:' + name;
    var cache = Twitch.storage.getObject(name, _.pick(options, 'storage'));
    if (!cache) { return null; }
    if ((cache.expiration && (new Date().getTime() - cache.time > cache.expiration)) ||
        options.version !== cache.version ||
        !_.isEqual(options.restrict, cache.restrict)) {
      Twitch.storage.del(name, _.pick(options, 'storage'));
      return null;
    }
    return cache.resource;
  };

  Twitch.mixin({
    cache: cache
  });

})(window.Twitch, window.jQuery);
