56ebe8d88c7a8a9f42cb72c63a51fbf785bfef6e
[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
6         var timeout = 180000,
7             service = {
8                 generateObj: function () {
9                     return new SyncObject();
10                 },
11             };
12
13         return service;
14
15         /**
16          * Base synchronization object
17          * @constructor
18          */
19         function SyncObject() {
20             this.runningRequests = [];
21             this.reqId = 0;
22             this.timeElapsed = 0;
23
24             this.spawnRequest = function (digest) {
25                 var id = digest + (this.reqId++).toString();
26                 this.runningRequests.push(id);
27                 // console.debug('adding request ',id,' total running requests  = ',this.runningRequests);
28                 return id;
29             };
30
31             this.removeRequest = function (id) {
32                 var index = this.runningRequests.indexOf(id);
33
34                 if (index > -1) {
35                     this.runningRequests.splice(index, 1);
36                     // console.debug('removing request ',id,' remaining requests = ',this.runningRequests);
37                 } else {
38                     console.warn('cannot remove request', id, 'from', this.runningRequests, 'index is', index);
39                 }
40             };
41
42             this.waitFor = function (callback) {
43                 var t = 1000,
44                     processes = this.runningRequests.length,
45                     self = this;
46
47                 if (processes > 0 && self.timeElapsed < timeout) {
48                     // console.debug('waitin on',processes,'processes',this.runningRequests);
49                     $timeout(function () {
50                         self.timeElapsed = self.timeElapsed + t;
51                         self.waitFor(callback);
52                     }, t);
53                 } else {
54                     callback();
55                 }
56             };
57         }
58     }
59
60     SyncService.$inject = ['$timeout'];
61
62     return SyncService;
63
64 });