summaryrefslogtreecommitdiff
path: root/www/js/EventCtrl.js
blob: 7422b03ad87128d60e7fd6b11dcb9cd97531f5f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/* jshint -W041 */
/* jslint browser: true*/
/* global cordova,StatusBar,angular,console */

// This is the controller for Event view. StateParams is if I recall the monitor ID.
// This was before I got access to the new APIs. FIXME: Revisit this code to see what I am doing with it
// and whether the new API has a better mechanism

angular.module('zmApp.controllers').controller('zmApp.EventCtrl', ['$ionicPlatform', '$scope', '$stateParams', 'message', 'ZMDataModel', '$ionicSideMenuDelegate', '$ionicModal', '$ionicLoading', '$http', '$state', '$window', function ($ionicPlatform, $scope, $stateParams, message, ZMDataModel, $ionicSideMenuDelegate, $ionicModal, $ionicLoading, $http, $state, $window) {
    console.log("I got STATE PARAM " + $stateParams.id);
    $scope.id = parseInt($stateParams.id, 10);
    $scope.connKey = Math.floor(Math.random() * (999999 - 111111 + 1)) + 111111;

    $scope.openMenu = function () {
        $ionicSideMenuDelegate.toggleLeft();
    };

    $scope.reloadView = function () {
        // All we really need to do here is change the random token
        // in the image src and it will refresh. No need to reload the view
        // and if you did reload the view, it would go back to events list
        // which is the view - and when you are in the modal it will go away
        console.log("*** Refreshing Modal view ***");
        //$state.go($state.current, {}, {reload: true});
        $scope.rand = Math.floor(Math.random() * (999999 - 111111 + 1)) + 111111;
        $ionicLoading.show({
            template: "refreshed view",
            noBackdrop: true,
            duration: 3000
        });

    };

    $scope.$on('$ionicView.loaded', function () {
        console.log("**VIEW ** Events Ctrl Loaded");
    });

    $scope.$on('$ionicView.enter', function () {
        console.log("**VIEW ** Events Ctrl Entered");
    });

    $scope.$on('$ionicView.leave', function () {
        console.log("**VIEW ** Events Ctrl Left");
    });

    $scope.$on('$ionicView.unloaded', function () {
        console.log("**VIEW ** Events Ctrl Unloaded");
        console.log("*** MODAL ** Destroying modal too");
        if ($scope.modal !== undefined) {
            $scope.modal.remove();
        }

    });


    // These are the commands ZM uses to move around
    // in ZMS
    var eventCommands = {
        next: "13",
        previous: "12",
        zoomin: "8",
        zoomout: "9",
        stop: "3",
        pause: "1",
        play: "2"
    };

    var eventsPage = 1;
    var moreEvents = true;
    $scope.viewTitle = {
        title: ""
    };

    // for some reason inifinite scroll is invoked
    // before I actually load the first page with page count
    // this makes scrolling stop as eventsPage is still 0
    // FIXME: This is a hack

    var pageLoaded = false;

    // When loading images, it sometimes takes time -  the images can be quite
    // large. What practically was happening was you'd see a blank screen for a few
    // seconds. Not a good UX. So what I am doing is when the events modal or
    // monitor modal is loaded, I show an ionic loading. And then when the first frame
    // finishes loading, I take it away

    $scope.finishedLoadingImage = function () {
        console.log("*** Events image FINISHED loading ***");
        $ionicLoading.hide();
    };

    $scope.eventCommands = eventCommands;

    // this routine handles skipping through events
    // in different event views
    $scope.controlEventStream = function (cmd) {
        console.log("Command value " + cmd);

        if (ZMDataModel.isSimulated()) {
            var str = "simulation mode. no action taken";
            $ionicLoading.show({
                template: str,
                noBackdrop: true,
                duration: 3000
            });
            return;
        }

        $ionicLoading.hide();
        $ionicLoading.show({
            template: "please wait...",
            noBackdrop: true,
            duration: 15000,
        });

        var loginData = ZMDataModel.getLogin();

        var toast_blurb = "";
        switch (cmd) {
        case "13":
            toast_blurb = "moving to ";
            break;
        case "12":
            toast_blurb = "moving to ";
            break;
        case "8":
            toast_blurb = "zoomed into ";
            break;
        case "9":
            toast_blurb = "zoomed out of ";
            break;
        case "3":
            toast_blurb = "stopping playback for ";
            break;
        case "2":
            toast_blurb = "resuming playback for ";
            break;
        case "1":
            toast_blurb = "pausing playback for ";
            break;
        }


        // You need to POST commands to control zms
        // Note that I am url encoding the parameters into the URL
        // If I leave it as JSON, it gets converted to OPTONS due
        // to CORS behaviour and ZM/Apache don't seem to handle it

        console.log("POST: " + loginData.url + '/index.php');

        var req = $http({
            method: 'POST',
            /*timeout: 15000,*/
            url: loginData.url + '/index.php',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                //'Accept': '*/*',
            },
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" +
                        encodeURIComponent(obj[p]));
                var foo = str.join("&");
                console.log("****RETURNING " + foo);
                return foo;
            },

            data: {
                view: "request",
                request: "stream",
                connkey: $scope.connKey,
                command: cmd,
                user: loginData.username,
                pass: loginData.password
            }
        });
        req.success(function (resp) {

            console.log("SUCCESS: " + JSON.stringify(resp));
            var str = toast_blurb + "event:" + resp.status.event;
            console.log(str);
            $ionicLoading.hide();
            $ionicLoading.show({
                template: str,
                noBackdrop: true,
                duration: 2000
            });
        });

        req.error(function (resp) {
            console.log("ERROR: " + JSON.stringify(resp));
        });
    };

    // This is called when we first tap on an event to see
    // the feed. It's important to instantiate ionicModal here
    // as otherwise you'd instantiate it when the view loads
    // and our "Please wait loading" technique I explained
    //earlier won't work

    $scope.openModal = function (eid, ename, edur) {
        console.log("Open Modal");
        $scope.eventName = ename;
        $scope.eventId = eid;
        $scope.eventDur = Math.round(edur);
        $scope.loginData = ZMDataModel.getLogin();
        $scope.rand = Math.floor(Math.random() * (999999 - 111111 + 1)) + 111111;

        $ionicModal.fromTemplateUrl('templates/events-modal.html', {
                scope: $scope,
                animation: 'slide-in-up'
            })
            .then(function (modal) {
                $scope.modal = modal;

                $ionicLoading.show({
                    template: "please wait...",
                    noBackdrop: true,
                    duration: 10000
                });

                $scope.modal.show();

            });
    };

    // We need to destroy because we are instantiating
    // it on open
    $scope.closeModal = function () {
        console.log("Close & Destroy Modal");
        if ($scope.modal !== undefined) {
            $scope.modal.remove();
        }

    };
    //Cleanup the modal when we're done with it
    // I Don't think it ever comes here
    $scope.$on('$destroy', function () {
        console.log("Destroy Modal");
        if ($scope.modal !== undefined) {
            $scope.modal.remove();
        }
    });

    console.log("***CALLING EVENTS FACTORY");
    var lData = ZMDataModel.getLogin();
    $scope.monitors = message;

    // I am converting monitor ID to monitor Name
    // so I can display it along with Events
    // Is there a better way?

    $scope.events = [];

    // First get total pages and then
    // start from the latest. If this fails, nothing displays
    // FIXME: clean up error handling

    ZMDataModel.getEventsPages($scope.id)
        .then(function (data) {
            eventsPage = data.pageCount;
            console.log("TOTAL EVENT PAGES IS " + eventsPage);
            pageLoaded = true;
            $scope.viewTitle.title = data.count;
            ZMDataModel.getEvents($scope.id, eventsPage)

            .then(function (data) {
                console.log("EventCtrl Got events");
                //var events = [];
                var myevents = data;
                for (var i = 0; i < myevents.length; i++) {

                    myevents[i].Event.MonitorName = ZMDataModel.getMonitorName(myevents[i].Event.MonitorId);
                }


                $scope.events = myevents;
            });

        });




    $scope.moreDataCanBeLoaded = function () {
        return moreEvents;
    };

    $scope.loadMore = function () {

        // the events API does not return an error for anything
        // except greater page limits than reported

        console.log("***** LOADING MORE INFINITE SCROLL ****");
        eventsPage--;
        if ((eventsPage <= 0) && (pageLoaded)) {
            moreEvents = false;
            console.log("*** At Page " + eventsPage + ", not proceeding");
            return;
        }



        ZMDataModel.getEvents($scope.id, eventsPage)
            .then(function (data) {
                    console.log("Got new page of events with Page=" + eventsPage);
                    var myevents = data;
                    for (var i = 0; i < myevents.length; i++) {

                        myevents[i].Event.MonitorName = ZMDataModel.getMonitorName(myevents[i].Event.MonitorId);
                    }
                    $scope.events = $scope.events.concat(myevents);
                    console.log("Got new page of events");

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                },

                function (error) {
                    console.log("*** No More Events to Load, Stop Infinite Scroll ****");
                    moreEvents = false;
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
        //  $scope.$broadcast('scroll.infiniteScrollComplete');

    };

    $scope.isSimulated = function () {
        return ZMDataModel.isSimulated();
    };


    $scope.doRefresh = function () {
        console.log("***Pull to Refresh");
        $scope.events = [];

        ZMDataModel.getEventsPages($scope.id)
            .then(function (data) {
                eventsPage = data.pageCount;
                console.log("TOTAL EVENT PAGES IS " + eventsPage);
                pageLoaded = true;
                $scope.viewTitle.title = data.count;
                ZMDataModel.getEvents($scope.id, eventsPage)

                .then(function (data) {
                    console.log("EventCtrl Got events");
                    //var events = [];
                    var myevents = data;
                    for (var i = 0; i < myevents.length; i++) {

                        myevents[i].Event.MonitorName = ZMDataModel.getMonitorName(myevents[i].Event.MonitorId);
                    }


                    $scope.events = myevents;
                });

            });
    }; //dorefresh

}]);