var app = angular.module("WebEngine", []);

app.controller("myInput", ['$scope','$http', function($scope,$http) {
    $scope.editable = false;
    $scope.param = null;
    $scope.value = null;
    $scope.int_value = null;

    $scope.init = function(param,int_value){
        $scope.param = param;
        $scope.int_value = int_value !== 'undefined' && typeof int_value !== 'undefined' ? true : false;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
              'Content-Type':'text/json',
            },
            data: {
              action : 'get_value',
              param : $scope.param,
            },
            }).then(function successCallback(response) {
            if($scope.int_value){
              $scope.value = parseInt(response.data.value);
            }
            else{
              $scope.value = response.data.value;
            }
        }, function errorCallback(response) {
          alert("Error please try again...");
        });
    };
    $scope.edit = function(){
        $scope.editable = true;
    };
    $scope.save = function(){
        $scope.editable = false;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
                'Content-Type':'text/json',
            },
            data: {
                action : 'set_value',
                param : $scope.param,
                value : $scope.value,
            },
        }).then(function successCallback(response) {
            if(response.data.result == "OK"){
                if($scope.int_value){
                    $scope.value = parseInt(response.data.value);
                }
                else{
                    $scope.value = response.data.value;
                }
            }
            else {
              alert("Error value not valid or more than 32 characters.");
            }
        }, function errorCallback(response) {
            alert("Error please try again...");
        });
    };
    $scope.cancel = function(){
        $scope.editable = false;
    };
}]);

app.controller("getFileButton", ['$scope','$http', function($scope,$http) {
    $scope.action = null;
    $scope.loading = false;

    $scope.init = function(action){
        $scope.action = action;
    };
    $scope.click = function(){
        $scope.loading = true;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
              'Content-Type':'text/json',
            },
            responseType: 'blob',
            data: {
              action : $scope.action,
            },
        }).then(function successCallback(response) {
            var disposition = response.headers("Content-Disposition");
            var matches = /"([^"]*)"/.exec(disposition);
            var filename = (matches != null && matches[1] ? matches[1] : 'file.zip');

            // The actual download
            var blob = new Blob([response.data], { type: 'application/octet-stream' });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            $scope.loading = false;
        }, function errorCallback(response) {
            alert("Error please try again...");
            $scope.loading = false;
        });
    };
}]);

app.controller("getTextButton", ['$scope','$http', function($scope,$http) {
    $scope.action = null;
    $scope.loading = false;

    $scope.init = function(action){
        $scope.action = action;
    };
    $scope.click = function(){
      $scope.loading = true;
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          responseType: 'text',
          data: {
              action : $scope.action,
          },
      }).then(function successCallback(response) {
          var disposition = response.headers("Content-Disposition");
          var matches = /"([^"]*)"/.exec(disposition);
          var filename = (matches != null && matches[1] ? matches[1] : 'file.txt');

          // The actual download
          var blob = new Blob([response.data], { type: 'text/plain' });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          $scope.loading = false;
          document.body.removeChild(link);
      }, function errorCallback(response) {
          alert("Error please try again...");
          $scope.loading = false;
      });
    };
}]);

app.controller("rebootButton", ['$scope','$http', function($scope,$http) {
    $scope.click = function(){
        if(confirm("Are you sure you want reboot device?")){
            $http({
                method: 'POST',
                url: 'api.php',
                headers: {
                    'Content-Type':'text/json',
                },
                data: {
                    action : 'advanced_reboot',
                },
            }).then(function successCallback(response) {
                alert( "Rebooting...");
            }, function errorCallback(response) {
                alert("Error please try again...");
            });
        }
    };
}]);

app.controller("backupButton", ['$scope','$http', function($scope,$http) {
    $scope.loading = false;
    $scope.click = function(){
        $scope.loading = true;
        $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          data: {
              action : 'app_mgmt_backup',
          },
        }).then(function successCallback(response) {
            $scope.loading = false;
            if(response.data.result != "ERROR"){
              alert("ValvApp manually backuped.");
            }
            else {
            alert("Error please try again...");
            }
        }, function errorCallback(response) {
            $scope.loading = false;
            alert("Error please try again...");
        });
    };
}]);

app.controller("restoreValvApp", ['$scope','$http', function($scope,$http) {
    $scope.showList = false;
    $scope.disable = false;
    $scope.list = null;

    $scope.click = function(){
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          data: {
              action : 'app_mgmt_list',
          },
      }).then(function successCallback(response) {
          $scope.list = response.data.result;
          $scope.showList = true;
          $scope.disable = true;
      }, function errorCallback(response) {
          alert("Error please try again...");
      });
    };

    $scope.cancel = function(){
        $scope.showList = false;
        $scope.disable = false;
    };

    $scope.clickVV = function(vvName){
      if(confirm("Are you sure you want restore ValvApp \n" + vvName + " ?")){
        alert("ValvApp " + vvName + " will be restored, please click OK and wait for the device to reboot.");
        $scope.showList = false;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
                'Content-Type':'text/json',
            },
            data: {
                action : 'app_mgmt_restore',
                value : vvName,
            },
        }).then(function successCallback(response) {
            if(response.data.result == "OK"){
                alert( "ValvApp restored! Rebooting...");
            }
            else{
                alert("Error during ValvApp restoration...");
            }
            $scope.showList = false;
            $scope.disable = false;

        }, function errorCallback(response) {
            $scope.showList = false;
            $scope.disable = false;
            alert("Error please try again...");
        });
      }
    };


}]);

app.directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});

app.controller("importValvApp", ['$scope','$http', function($scope,$http) {
    $scope.file = null;
    $scope.loading = false;

    $scope.click = function(){
      if($scope.file == null || $scope.file.lenght == 0){
        alert("No ValvApp to import!");
      }
      else {
        if(confirm("Are you sure you want import ValvApp \n" + $scope.file[0].name + " ?")){
            $scope.loading = true;
            var fd = new FormData();
            fd.append("action", "app_mgmt_import");
            fd.append("file", $scope.file[0]);
            var xhr = new XMLHttpRequest();
            xhr.open('POST','api_file.php', true);
            xhr.responseType = "json";
            xhr.onload = function() {
                $scope.loading = false;
                if (this.status == 200 && this.response.result == "OK") {
                  alert( "ValvApp imported! Rebooting...");
                }else{
                  alert( "Error during ValvApp importation!");
                }
            };
            xhr.send(fd);
        }
        $scope.file = null;
      }
    };
}]);


app.controller("updateEngine", ['$scope','$http', function($scope,$http) {
    $scope.file = null;
    $scope.loading = false;

    $scope.click = function(){
      if($scope.file == null || $scope.file.lenght == 0){
        alert("No Engine to update!");
      }
      else {
        if(confirm("Are you sure you want update R-Engine with\n" + $scope.file[0].name + " ?\n\nNOTE: The upload of the engine package may take up to 10 minutes. Please, be patient.")){
            $scope.loading = true;
            var fd = new FormData();
            fd.append("action", "advanced_update");
            fd.append("file", $scope.file[0]);
            var xhr = new XMLHttpRequest();
            xhr.open('POST','api_file.php', true);
            xhr.responseType = "json";
            xhr.onload = function() {
                if (this.status == 200 && this.response.result == "OK") {
                    $scope.status();
                }else{
                    alert("Error during R-Engine importation.");
                    $scope.loading = false;
                }
            };
            xhr.send(fd);
        }else{
          $scope.file = null;
        }
      }
    };

    $scope.status = function(){
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          data: {
              action : 'advanced_update_status',
          },
      }).then(function successCallback(response) {
        if(response.data.status == "WAIT"){
            $scope.status();
        }else if(response.data.status == "ERROR") {
            alert("Error during R-Engine importation.");
            $scope.loading = false;
        }else if(response.data.status == "OK"){
            $scope.loading = false;
            alert("R-Engine " + $scope.file[0].name + " will be installed, please click OK and wait for the device to reboot several time.");
            $scope.reboot();
        }else {
          alert("Error " + response.data.status);
          $scope.loading = false;
        }
      }, function errorCallback(response) {
          alert("Error please try again...");
          $scope.loading = false;
      });
    };

    $scope.reboot = function(){
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          data: {
              action : 'advanced_reboot',
          },
      }).then(function successCallback(response) {
      }, function errorCallback(response) {
          alert("Error please try again...");
      });
    };

}]);

app.controller("checkbox", ['$scope','$http', function($scope,$http) {
    $scope.checked = null;

    $scope.init = function(param){
        $scope.param = param;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
                'Content-Type':'text/json',
            },
            data: {
                action : 'get_value',
                param : $scope.param,
            },
        }).then(function successCallback(response) {
            $scope.checked = parseInt(response.data.value) == 1 ? true : false;
        }, function errorCallback(response) {
            alert("Error please try again...");
        });
    };

    $scope.change = function(){
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
                'Content-Type':'text/json',
            },
            data: {
                action : 'set_value',
                param : $scope.param,
                value : $scope.checked ? 1 : 0,
            },
        }).then(function successCallback(response) {
            $scope.checked = parseInt(response.data.value) == 1 ? true : false;
        }, function errorCallback(response) {
            alert("Error please try again...");
        });
    };

}]);


app.controller("myRadioboxCtrl", ['$scope','$http', function($scope,$http) {
    $scope.value = "1";
    $scope.loading = false;

    $scope.click = function(){
        $scope.loading = true;
        $http({
            method: 'POST',
            url: 'api.php',
            headers: {
                'Content-Type':'text/json',
            },
            data: {
                action : 'logging_export',
                value : $scope.value,
            },
        }).then(function successCallback(response) {
            if(response.data.result == "OK"){
                $scope.status();
            }
            else{
                $scope.loading = false;
                alert("Error during export...");
            }
        }, function errorCallback(response) {
            $scope.loading = false;
            alert("Error please try again...");
        });
    };

    $scope.status = function(){
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          data: {
              action : 'logging_export_status',
          },
      }).then(function successCallback(response) {
        if(response.data.status == "WAIT"){
            $scope.status();
        }else if(response.data.status == "ERROR") {
            $scope.loading = false;
            alert("Error during export...");
        }else if(response.data.status.length > 3){
            $scope.download(response.data.status);
        }else {
            $scope.loading = false;
          alert("Error " + response.data.status);
        }
      }, function errorCallback(response) {
          $scope.loading = false;
          alert("Error please try again...");
      });
    };

    $scope.download = function(path){
      $http({
          method: 'POST',
          url: 'api.php',
          headers: {
              'Content-Type':'text/json',
          },
          responseType: 'blob',
          data: {
              action : 'logging_export_download',
              value : path,
          },
      }).then(function successCallback(response) {
          var disposition = response.headers("Content-Disposition");
          var matches = /"([^"]*)"/.exec(disposition);
          var filename = (matches != null && matches[1] ? matches[1] : 'file.zip');

          // The actual download
          var blob = new Blob([response.data], { type: 'application/zip' });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          $scope.loading = false;
      }, function errorCallback(response) {
          $scope.loading = false;
          alert("Error please try again...");
      });
    };
}]);
