blob: f940ca72966c4909f0ff0d9df3d9acb6ee356631 [file] [log] [blame]
Simon Huntc7ae7952015-04-08 18:59:27 -07001/*
2 * Copyright 2015 Open Networking Laboratory
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
17/*
18 ONOS GUI -- Util -- User Preference Service
19 */
20(function () {
21 'use strict';
22
23 // injected refs
24 var $log, $cookies;
25
26 // internal state
27 var cache = {};
28
29 // NOTE: in Angular 1.3.5, $cookies is just a simple object, and
30 // cookie values are just strings. From the 1.3.5 docs:
31 //
32 // "Only a simple Object is exposed and by adding or removing
33 // properties to/from this object, new cookies are created/deleted
34 // at the end of current $eval. The object's properties can only
35 // be strings."
36 //
37 // We may want to upgrade the version of Angular sometime soon
38 // since later version support objects as cookie values.
39
40 // NOTE: prefs represented as simple name/value(number) pairs
41 // => a temporary restriction while we are encoding into cookies
42 /*
43 {
44 foo: 1,
45 bar: 0,
46 goo: 2
47 }
48
49 stored as "foo:1,bar:0,goo:2"
50 */
51
52 // reads cookie with given name and returns an object rep of its value
53 // or null if no such cookie is set
54 function getPrefs(name) {
55 var cook = $cookies[name],
56 bits,
57 obj = {};
58
59 if (cook) {
60 bits = cook.split(',');
61 bits.forEach(function (value) {
62 var x = value.split(':');
63 obj[x[0]] = Number(x[1]);
64 });
65
66 // update the cache
67 cache[name] = obj;
68 return obj;
69 }
70 // perhaps we have a cached copy..
71 return cache[name];
72 }
73
74 function setPrefs(name, obj) {
75 var bits = [],
76 str;
77
78 angular.forEach(obj, function (value, key) {
79 bits.push(key + ':' + value);
80 });
81 str = bits.join(',');
82
83 // keep a cached copy of the object
84 cache[name] = obj;
85
86 // The angular way of doing this...
87 // $cookies[name] = str;
88 // ...but it appears that this gets delayed, and doesn't 'stick' ??
89
90 // FORCE cookie to be set by writing directly to document.cookie...
91 document.cookie = name + '=' + encodeURIComponent(str);
92 $log.debug('<<>> Wrote cookie <'+name+'>:', str);
93 }
94
95 angular.module('onosUtil')
96 .factory('PrefsService', ['$log', '$cookies',
97 function (_$log_, _$cookies_) {
98 $log = _$log_;
99 $cookies = _$cookies_;
100
101 return {
102 getPrefs: getPrefs,
103 setPrefs: setPrefs
104 };
105 }]);
106
107}());