/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true */
/*global require, csInterface, module */

// Least recently used (LRU) cache. Oldest items are evicted first.
(function () {
    "use strict";

    var _ = require("underscore");

    var LRUCache = function (maxCacheEntries) {
        this._maxCacheEntries = maxCacheEntries || 1000;
        this.reset();
    };

    LRUCache.prototype.set = function (key, value) {
        var purgedKey;
        if (key == null || value === undefined) {
            return;
        }

        this.unset(key);

        if (this._keys.length >= this._maxCacheEntries) {
            purgedKey = _(this._keys).first();
            this.unset(purgedKey);
        }

        this._cache[key] = value;
        this._keys.push(key);
        return purgedKey;
    };

    LRUCache.prototype.get = function (key) {
        return this._cache[key];
    };

    LRUCache.prototype.unset = function (key) {
        if (this._cache[key] === undefined) {
            return;
        }

        this._keys = _(this._keys).without(key);
        delete this._cache[key];
    };

    LRUCache.prototype.serialize = function() {
        return this._cache;
    };

    LRUCache.prototype.reset = function () {
        this._cache = {};
        this._keys = [];
    };

    module.exports = LRUCache;
}());
