1window.angular && (function(angular) {
2  'use strict';
3
4  angular.module('app.common.directives').directive('appHeader', [
5    'APIUtils',
6    function(APIUtils) {
7      return {
8        'restrict': 'E',
9        'template': require('./app-header.html'),
10        'scope': {'path': '='},
11        'controller': [
12          '$rootScope', '$cookies', '$scope', 'dataService', 'userModel',
13          '$location', '$route',
14          function(
15              $rootScope, $cookies, $scope, dataService, userModel, $location,
16              $route) {
17            $scope.dataService = dataService;
18            $scope.username = '';
19
20            try {
21              // Create a secure websocket with URL as /subscribe
22              // TODO: Need to put in a generic APIUtils to avoid duplicate
23              // controller
24              var token = $cookies.get('XSRF-TOKEN');
25              var ws = new WebSocket(
26                  'wss://' + dataService.server_id + '/subscribe', [token]);
27            } catch (error) {
28              console.log('WebSocket', error);
29            }
30
31            if (ws !== undefined) {
32              // Specify the required event details as JSON dictionary
33              var data = JSON.stringify({
34                'paths': ['/xyz/openbmc_project/state/host0'],
35                'interfaces': ['xyz.openbmc_project.State.Host']
36              });
37
38              // Send the JSON dictionary data to host
39              ws.onopen = function() {
40                ws.send(data);
41                console.log('host0 ws opened');
42              };
43
44              // Close the web socket
45              ws.onclose = function() {
46                console.log('host0 ws closed');
47              };
48
49              // Websocket event handling function which catches the
50              // current host state
51              ws.onmessage = function(evt) {
52                // Parse the response (JSON dictionary data)
53                var content = JSON.parse(evt.data);
54
55                // Fetch the current server power state
56                if (content.hasOwnProperty('properties') &&
57                    content['properties'].hasOwnProperty('CurrentHostState')) {
58                  // Refresh the host state and status
59                  // TODO: As of now not using the current host state
60                  // value for updating the data Service state rather
61                  // using it to detect the command line state change.
62                  // Tried different methods like creating a separate
63                  // function, adding ws under $scope etc.. but auto
64                  // refresh is not happening.
65                  $scope.loadServerStatus();
66                }
67              };
68            }
69
70            $scope.loadServerHealth = function() {
71              APIUtils.getLogs().then(function(result) {
72                dataService.updateServerHealth(result.data);
73              });
74            };
75
76            $scope.loadServerStatus = function() {
77              if (!userModel.isLoggedIn()) {
78                return;
79              }
80              APIUtils.getHostState().then(
81                  function(status) {
82                    if (status ==
83                        'xyz.openbmc_project.State.Host.HostState.Off') {
84                      dataService.setPowerOffState();
85                    } else if (
86                        status ==
87                        'xyz.openbmc_project.State.Host.HostState.Running') {
88                      dataService.setPowerOnState();
89                    } else {
90                      dataService.setErrorState();
91                    }
92                  },
93                  function(error) {
94                    console.log(error);
95                  });
96            };
97
98            $scope.loadNetworkInfo = function() {
99              if (!userModel.isLoggedIn()) {
100                return;
101              }
102              APIUtils.getNetworkInfo().then(function(data) {
103                dataService.setNetworkInfo(data);
104              });
105            };
106
107            $scope.loadSystemName = function() {
108              // Dynamically get ComputerSystems Name/serial
109              // which differs across OEM's
110              APIUtils.getRedfishSysName().then(
111                  function(res) {
112                    dataService.setSystemName(res);
113                  },
114                  function(error) {
115                    console.log(JSON.stringify(error));
116                  });
117            };
118
119            function loadData() {
120              $scope.loadServerStatus();
121              $scope.loadNetworkInfo();
122              $scope.loadServerHealth();
123              $scope.loadSystemName();
124              $scope.username = dataService.getUser();
125            }
126
127            loadData();
128
129            $scope.logout = function() {
130              userModel.logout(function(status, error) {
131                if (status) {
132                  $location.path('/logout');
133                } else {
134                  console.log(error);
135                }
136              });
137            };
138
139            $scope.refresh = function() {
140              // reload current page controllers and header
141              loadData();
142              $route.reload();
143              // Add flash class to header timestamp on click of refresh
144              var myEl =
145                  angular.element(document.querySelector('.header__refresh'));
146              myEl.addClass('flash');
147              setTimeout(function() {
148                myEl.removeClass('flash');
149              }, 2000);
150            };
151
152            var loginListener =
153                $rootScope.$on('user-logged-in', function(event, arg) {
154                  loadData();
155                });
156
157            $scope.$on('$destroy', function() {
158              loginListener();
159            });
160          }
161        ]
162      };
163    }
164  ]);
165})(window.angular);
166