a83505125686982d65a1cb2ab0851bb2a2cad1ae
[dlux.git] / modules / common-yangutils-resources / src / main / resources / yangutils / services / sync.services.js
1 define([], function () {
2     'use strict';
3
4     function SyncService($timeout){
5         var timeout = 180000;
6
7         var SyncObject = function () {
8             this.runningRequests = [];
9             this.reqId = 0;
10             this.timeElapsed = 0;
11
12             this.spawnRequest = function (digest) {
13                 var id = digest + (this.reqId++).toString();
14                 this.runningRequests.push(id);
15                 //console.debug('adding request ',id,' total running requests  = ',this.runningRequests);
16                 return id;
17             };
18
19             this.removeRequest = function (id) {
20                 var index = this.runningRequests.indexOf(id);
21
22                 if (index > -1) {
23                     this.runningRequests.splice(index, 1);
24                     //console.debug('removing request ',id,' remaining requests = ',this.runningRequests);
25                 } else {
26                     console.warn('cannot remove request', id, 'from', this.runningRequests, 'index is', index);
27                 }
28             };
29
30             this.waitFor = function (callback) {
31                 var t = 1000,
32                     processes = this.runningRequests.length,
33                     self = this;
34
35                 if (processes > 0 && self.timeElapsed < timeout) {
36                     // console.debug('waitin on',processes,'processes',this.runningRequests);
37                     $timeout(function () {
38                         self.timeElapsed = self.timeElapsed + t;
39                         self.waitFor(callback);
40                     }, t);
41                 } else {
42                     callback();
43                 }
44             };
45         };
46
47         return {
48             generateObj: function () {
49                 return new SyncObject();
50             }
51         };
52     }
53
54     SyncService.$inject=['$timeout'];
55
56     return SyncService;
57
58 });