1window.angular && (function(angular) {
2  'use strict';
3
4  angular.module('app.common.directives').directive('certificate', [
5    'APIUtils',
6    function(APIUtils) {
7      return {
8        'restrict': 'E',
9        'template': require('./certificate.html'),
10        'scope': {'cert': '=', 'reload': '&'},
11        'controller': [
12          '$scope', 'APIUtils', 'toastService',
13          function($scope, APIUtils, toastService) {
14            var certificateType = 'PEM';
15            $scope.replaceCertificate = function(certificate) {
16              $scope.loading = true;
17              if (certificate.file.name.split('.').pop() !==
18                  certificateType.toLowerCase()) {
19                toastService.error(
20                    'Certificate must be replaced with a .pem file.');
21                return;
22              }
23              var file =
24                  document
25                      .getElementById(
26                          'upload_' + certificate.Description + certificate.Id)
27                      .files[0];
28              var reader = new FileReader();
29              reader.onloadend = function(e) {
30                var data = {};
31                data.CertificateString = e.target.result;
32                data.CertificateUri = {'@odata.id': certificate['@odata.id']};
33                data.CertificateType = certificateType;
34                APIUtils.replaceCertificate(data).then(
35                    function(data) {
36                      $scope.loading = false;
37                      toastService.success(
38                          certificate.Description + ' was replaced.');
39                      $scope.reload();
40                    },
41                    function(error) {
42                      console.log(error);
43                      $scope.loading = false;
44                      toastService.error(
45                          'Unable to replace ' + certificate.Description);
46                    });
47              };
48              reader.readAsBinaryString(file);
49            };
50          }
51        ]
52      };
53    }
54  ]);
55})(window.angular);
56