/*jshint -W100*/
/**
 * Each section of the site has its own module. It probably also has
 * submodules, though this boilerplate is too simple to demonstrate it. Within
 * `src/app/home`, however, could exist several additional folders representing
 * additional modules that would then be listed as dependencies of this one.
 * For example, a `note` section could have the submodules `note.create`,
 * `note.delete`, `note.edit`, etc.
 *
 * Regardless, so long as dependencies are managed correctly, the build process
 * will automatically take take of the rest.
 *
 * The dependencies block here is also where component dependencies should be
 * specified, as shown below.
 */
angular.module( 'ngBoilerplate.admin_modify_db', [
  'ui.router',
  'plusOne',
  'ngBoilerplate.account',
  'ngBoilerplate.activeIngredient',
  'ngBoilerplate.users',
  'ngBoilerplate.home',
  'ngBoilerplate.admin',
  'ngBoilerplate.admin_mail_list',
  'ngBoilerplate.admin_suggestions',
  'ngBoilerplate.admin_users',
  'angular-md5'
])

/**
 * Each section or module of the site can also have its own routes. AngularJS
 * will handle ensuring they are all available at run-time, but splitting it
 * this way makes each module more "self-contained".
 */
.config(function config( $stateProvider ) {
  $stateProvider.state( 'admin_modify_db', {
    url: '/admin_modify_db',
    views: {
       "header": {
        controller: 'Admin_modify_db_Ctrl',
        templateUrl: 'header/header.tpl.html'
      },
      "admin_header": {
        controller: 'Admin_modify_db_Ctrl',
        templateUrl: 'admin_header/admin_header.tpl.html'
      },
      "main": {
        controller: 'Admin_modify_db_Ctrl',
        templateUrl: 'admin_modify_db/admin_modify_db.tpl.html'
      },
      "footer": {
        controller: 'Admin_modify_db_Ctrl',
        templateUrl: 'footer/footer.tpl.html'
      }
    },
    data:{ pageTitle: 'Modificar base de datos' },
    resolve:{
        activeIngredients: function(activeIngredientService) {
            console.log("activeIngredients");
            return activeIngredientService.getAllActiveIngredients();
        }
    }
  });
})

/**
 * And of course we define a controller for our route.
 */
.controller( 'Admin_modify_db_Ctrl', function Admin_modify_db_Ctrl( $scope, sessionService, activeIngredients, activeIngredientService, $state, $http, md5) {
    console.log("Admin_modify_db_Ctrl");
    $scope.activeIngredients = activeIngredients;
    $scope.isLoggedIn = sessionService.isLoggedIn;
    $scope.isAdmin = sessionService.isAdmin;
    $scope.isUser = sessionService.isUser;
    $scope.isTempUser = sessionService.isTempUser;
    $scope.logout = function() {
        sessionService.logout();
        $state.go("home");
    };
    /*$scope.uploadExcel = function() {
        console.log("Admin_modify_db_Ctrl - uploadExcel");
        activeIngredientService.uploadExcel($scope.excelCsv1, function() {
                alert("Excel 1 carregat Correctament");
                window.location.reload();
        },
        function() {
            alert("Error en la carrega de l'excel 1");
        });
    };
    $scope.uploadExcelRecomendations = function() {
        console.log("Admin_modify_db_Ctrl - uploadExcelRecomendations");
        activeIngredientService.uploadExcelRecomendations($scope.excelCsv2, function() {
                alert("Excel 2 carregat Correctament");
                window.location.reload();
        },
        function() {
            alert("Error en la carrega de l'excel 2");
        });
    };*/
    $scope.showContent1 = function($fileContent){
        console.log("Admin_modify_db_Ctrl - uploadExcel");
        activeIngredientService.uploadExcel($fileContent, function() {
                alert("Excel de principios activos cargado correctamente");
                window.location.reload();
        },
        function() {
            alert("Error en la carga del excel de principios activos");
        });
    };
    $scope.showContent2 = function($fileContent){
        console.log("Admin_modify_db_Ctrl - uploadExcelRecomendations");
        activeIngredientService.uploadExcelRecomendations($fileContent, function() {
                alert("Excel de recomendaciones cargado correctamente");
                window.location.reload();
        },
        function() {
            alert("Error en la carga del excel de recomendaciones");
        });
    };
    $scope.deleteActiveIngredients = function() {
        console.log("deleteActiveIngredients");
        return $http.post("/basic-web-app/rest/activeIngredients/clearTable", "name=" + localStorage.getItem("name") + "&password=" +md5.createHash($scope.deleteActiveIngredientsPassword || ''), {
            headers:{'Content-Type':'application/x-www-form-urlencoded'}
        }
        ).then(function(data){
            alert('Borrado de principios activos completado');
            window.location.reload();
        }, function(data){
            alert("Contraseņa incorrecta");
        });
    };
})



.directive('onReadFile', function ($parse) {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, element, attrs) {
            var fn = $parse(attrs.onReadFile);
            element.on('change', function(onChangeEvent) {
                var reader = new FileReader();
                reader.onload = function(onLoadEvent) {
                    scope.$apply(function() {
                        fn(scope, {$fileContent:onLoadEvent.target.result});
                    });
                };
                reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
            });
        }
    };
});

