'use strict';
/**
 * @ngdoc directive
 * @name download
 * @description
 *  다운로드 메뉴 Start button directive
 */
app.directive('download', function download() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      user: '=',
      text: '@'
    },
    template: '<button class="btn btn-primary" ng-click="start()">{{text}}</button>',
    controller: function ($scope, $interval, $modal, toastr, Systems) {
      $scope.percentage = 0;

      // 다운로드 modal popup
      var dlModal = $modal({ 
        scope: $scope, 
        backdrop: 'static', 
        template: 'views/modal-tpls/dl-popup.html', 
        show: false
      });

      // modal 보이기
      function showModal() {
        dlModal.$promise.then(dlModal.show);
      }

      // 다운로드 시작
      $scope.start = function () {
        showModal();
        $scope.isDone = false;
        $scope.percentage = 0;
        $scope.downloadStatus = 'Generating...';

        // Download Data Generate
        Systems.prepareDownload().then(function(response) {
          if(response.data.result) {

            var systemId = $scope.systemId;
            $scope.downloadStatus = 'Downloading...';

            // 서버와 통신할 때 다른 곳에서는 $http 를 사용하는데 여기서만 $.ajax 를 사용하고 있음
            // XMLHttpRequest 를 확장해서 progress (여기서는 다운로드 진행률) 을 얻음
            $.ajax({
                // 다운로드 progress 를 표시해주기 위해 XMLHttpRequest 를 확장해서 xhr 을 설정
                xhr: function() {
                  var xhr = new window.XMLHttpRequest();
                  xhr.addEventListener("progress", function(evt) {
                    var responseData = evt.currentTarget.response;
                    var lines = responseData.split(";");
                    var progress = 0;
                    if(lines.length) {
                      progress = lines[lines.length-1];
                    }   
                    else {
                      progress = 0;
                    }

                    if(progress.substr(0, 5) === 'ERROR') {
                      $scope.$apply(function() { 
                        $scope.downloadStatus = 'Failed to download.'; 
                        $scope.isDone = true;
                      });
                      return;
                    }

                    if(progress >= 100) {
                      //dlModal.hide();
                      $scope.$apply(function() {
                        $scope.isDone = true;
                        $scope.percentage = 100;
                        $scope.downloadStatus = 'Download finished.';
                      });
                      return;
                    }

                    $scope.$apply(function() { $scope.percentage = progress; });
                  }, false);

                  return xhr;
                },
                type: 'POST',
                url: '/api/download/server_start/' + systemId,    // 다운로드 시작 API
                headers: {
                  Authorization: 'Bearer ' + $scope.user.token
                },
                error: function (xhr, ajaxOptions, thrownError) {
                  $scope.$apply(function() { $scope.downloadStatus = 'Error'; });
                }
              });
          } else {
            $scope.downloadStatus = response.data.error;
          }
        }, function(error) {
          toastr.error('Please try again');
        });
      };

      // 다운로드 정지
      $scope.stop = function() {
        console.log('Fired stop function');

        Systems.stopDownload().then(function(response) {
          console.log(response);
        });
      };
    }
  };
});
