1/**
2 * Controller for power-usage
3 *
4 * @module app/serverControl
5 * @exports powerUsageController
6 * @name powerUsageController
7 */
8
9window.angular && (function(angular) {
10  'use strict';
11
12  angular.module('app.serverControl').controller('powerUsageController', [
13    '$scope', '$window', 'APIUtils', '$route', '$q',
14    function($scope, $window, APIUtils, $route, $q) {
15      $scope.power_consumption = '';
16      $scope.power_cap = {};
17      $scope.set_power_cap_error = false;
18      $scope.set_power_cap_success = false;
19      $scope.loading = false;
20      loadPowerData();
21
22      function loadPowerData() {
23        $scope.loading = true;
24
25        var getPowerCapPromise = APIUtils.getPowerCap().then(
26            function(data) {
27              $scope.power_cap = data.data;
28            },
29            function(error) {
30              console.log(JSON.stringify(error));
31            });
32
33        var getPowerConsumptionPromise = APIUtils.getPowerConsumption().then(
34            function(data) {
35              $scope.power_consumption = data;
36            },
37            function(error) {
38              console.log(JSON.stringify(error));
39            });
40
41        var promises = [
42          getPowerConsumptionPromise,
43          getPowerCapPromise,
44        ];
45
46        $q.all(promises).finally(function() {
47          $scope.loading = false;
48        });
49      }
50
51      $scope.setPowerCap = function() {
52        $scope.set_power_cap_error = false;
53        $scope.set_power_cap_success = false;
54        // The power cap value will be undefined if outside range
55        if (!$scope.power_cap.PowerCap) {
56          $scope.set_power_cap_error = true;
57          return;
58        }
59        $scope.loading = true;
60        var promises = [
61          setPowerCapValue(),
62          setPowerCapEnable(),
63        ];
64
65        $q.all(promises).finally(function() {
66          $scope.loading = false;
67          if (!$scope.set_power_cap_error) {
68            $scope.set_power_cap_success = true;
69          }
70        });
71      };
72      $scope.refresh = function() {
73        $route.reload();
74      };
75
76      function setPowerCapValue() {
77        return APIUtils.setPowerCap($scope.power_cap.PowerCap)
78            .then(
79                function(data) {},
80                function(error) {
81                  $scope.set_power_cap_error = true;
82                  console.log(JSON.stringify(error));
83                });
84      }
85
86      function setPowerCapEnable() {
87        return APIUtils.setPowerCapEnable($scope.power_cap.PowerCapEnable)
88            .then(
89                function(data) {},
90                function(error) {
91                  $scope.set_power_cap_error = true;
92                  console.log(JSON.stringify(error));
93                });
94      }
95    }
96  ]);
97})(angular);
98