blob: 4994953f1c00893fdf6bb55ad047dc8ecadbb6cb [file] [log] [blame]
Chinthakayala, Sheshashailavas (sc2914)d1569972017-08-28 05:25:46 -09001/**
2 * Copyright 2014 IBM Corp.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 **/
16
17var when = require("when");
18
19var assert = require("assert");
20
21var userSettings = null;
22var globalSettings = null;
23var storage = null;
24
25var persistentSettings = {
26 init: function(settings) {
27 userSettings = settings;
28
29 for (var i in settings) {
30 if (settings.hasOwnProperty(i)) {
31 (function() {
32 var j = i;
33 persistentSettings.__defineGetter__(j,function() { return userSettings[j]; });
34 persistentSettings.__defineSetter__(j,function() { throw new Error("Property '"+i+"' is read-only"); });
35 })();
36 }
37 }
38 globalSettings = null;
39 },
40 load: function(_storage) {
41 storage = _storage;
42 return storage.getSettings().then(function(_settings) {
43 globalSettings = _settings;
44 });
45 },
46 get: function(prop) {
47 if (userSettings.hasOwnProperty(prop)) {
48 return userSettings[prop];
49 }
50 if (globalSettings === null) {
51 throw new Error("Settings not available");
52 }
53 return globalSettings[prop];
54 },
55
56 set: function(prop,value) {
57 if (userSettings.hasOwnProperty(prop)) {
58 throw new Error("Property '"+prop+"' is read-only");
59 }
60 if (globalSettings === null) {
61 throw new Error("Settings not available");
62 }
63 var current = globalSettings[prop];
64 globalSettings[prop] = value;
65 try {
66 assert.deepEqual(current,value);
67 return when.resolve();
68 } catch(err) {
69 return storage.saveSettings(globalSettings);
70 }
71 },
72
73 available: function() {
74 return (globalSettings !== null);
75 },
76
77 reset: function() {
78 userSettings = null;
79 globalSettings = null;
80 storage = null;
81 }
82}
83
84module.exports = persistentSettings;