/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2014 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, node: true */

var _ = require("underscore");

(function () {
    
    "use strict";
    
    var setPref = function(name, val) {
        if (global.localStorage) {
            global.localStorage.setItem(name, val);
        }
    };
    
    var getPref = function (name) {
        if (global.localStorage) {
            return global.localStorage.getItem(name);
        }
        return null;
    };
    
    var getMRUList = function (mruKey) {
        var mruArrayString = module.exports.getPref(mruKey),
            mruList = [];
        if (!mruArrayString) {
            return mruList;
        }
        try {
            mruList = JSON.parse(mruArrayString);
        } catch (e) {
        }
        return mruList;
    };
    
    var getMRUPref = function (mruKey, itemKey) {
        var mruList = module.exports.getMRUList(mruKey);
        return _.findWhere(mruList, itemKey);
    };
    
    var setMRUPref = function (mruKey, itemKey, itemToSet, maxMRU) {
        var mruList = module.exports.getMRUList(mruKey) || [],
            existing = _.findWhere(mruList, itemKey);
        mruList = _.without(mruList, existing);
        mruList.unshift(itemToSet);
        mruList = _.first(mruList, maxMRU || 100);
        module.exports.setPref(mruKey, JSON.stringify(mruList));
    };
    
    module.exports = {
        getPref: getPref,
        setPref: setPref,
        getMRUList: getMRUList,
        getMRUPref: getMRUPref,
        setMRUPref: setMRUPref
    };
    
}());


