app.controller("responsavelController", function ($scope, $modal, $log, $http, dataService, responsavelFactory, notificationFactory, httpRequestFactory, $rootScope) {
    $scope.responsaveis = [];
    $scope.resLocal = [];


    $scope.carregarResponsaveis = function () {
        var getSuccessCallback = function (data, status) {
            data.unshift({
                Pk_Responsavel: 0,
                Nome: '<Sem gestor>',
                NIF: '',
                IdUtilizador: 0
            });
            $scope.responsaveis = data;
            
        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        responsavelFactory.getResponsaveis().success(getSuccessCallback).error(errorCallback);
    };


    $scope.inserirResponsavel = function (item) {

        if (item == null)
            return;

        var successCallback = function (data, status, headers, config) {
            notificationFactory.success(data);
            $scope.carregarResponsaveis();
        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        responsavelFactory.addResponsavel(item).success(successCallback).error(errorCallback);
    };

    $scope.updateResponsavel = function (elem) {
        if (elem == null)
            return;



        var successCallback = function (data, status, headers, config) {
            notificationFactory.success(data);

        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        responsavelFactory.updateResponsavel(elem).success(successCallback).error(errorCallback);
    };

    $scope.apagarResponsavel = function (elem) {
        if (elem == null)
            return;


        var successCallback = function (data, status, headers, config) {

            //$scope.carregarResponsaveis();
            notificationFactory.success(data);
            var arr = $scope.responsaveis;
            for (i = 0; i < arr.length; i++) {
                if (arr[i] == elem) {
                    arr.splice(i, 1);

                    break;

                }
            }
            $scope.selectedResponsavel = null;
        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        responsavelFactory.deleteResponsavel(elem).success(successCallback).error(errorCallback);
    };

    $scope.confirmarApagarResponsavel = function (row) {

        if (row == null)
            return;

        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalConfirmarApagar.html?v=' + new Date(),
            controller: 'modalController',
            resolve: {

                items: function () { return row; },

                //  isNew: false
            }
        });

        modalInstance.result.then(function (item) {

            $scope.apagarResponsavel(item);

        }, function () {

        });

    };

    $scope.selResponsavel = function (row) {
        $scope.selectedResponsavel = row;

    };

    $scope.responsavelEditRow = function (row) {
        if (row == null) {
            row = {
                Pk_Responsavel: 0,
                Nome: "Nome",
                NIF: "",
                IdUtilizador: 0
            };
            row.op = "Novo";
            $scope.editarResponsavel(row);
        }
        else {
            if (row.Pk_Responsavel == 0)
                return;

            row.op = "Editar";
           
            var isNumero = $scope.isNumeric(row.NIF);
            if (isNumero == true) {
                if (Number(row.NIF) < 400000000) {
                    $scope.confirmarDadosSensiveis(row);
                }
                else
                    $scope.editarResponsavel(row);

                return;
            }

            $scope.editarResponsavel(row);
        }

        
    };

    $scope.editarResponsavel = function (row) {
                
        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalEditarResponsavel.html?v=' + new Date(),
            controller: 'modalController',
            backdrop: 'static',
            keyboard: false,
            resolve: {

                items: function () { return row; },

                //  isNew: false
            }
        });

        modalInstance.result.then(function (item) {

            if (item.op == "Editar") {
                $scope.selectedResponsavel = item;
                $scope.updateResponsavel(item);
            }
            else {

                $scope.inserirResponsavel(item);
            }
            

        }, function () {

        });

    };

   
    //Responsavel Local
    $scope.carregarResLocal = function () {
        var getSuccessCallback = function (data, status) {

            $scope.resLocal = data;

        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data.ExceptionMessage);
        };

        responsavelFactory.getResLocal().success(getSuccessCallback).error(errorCallback);
    };



   

    //$scope.inserirResLocal = function (item) {

    //    if (item == null)
    //        return;

    //    var successCallback = function (data, status, headers, config) {
    //        notificationFactory.success(data);
    //        $scope.carregarResLocal();
    //    };


    //    var errorCallback = function (data, status, headers, config) {
    //        notificationFactory.error(data);
    //    };

    //    responsavelFactory.addResLocal(item).success(successCallback).error(errorCallback);
    //};

    //$scope.updateResLocal = function (elem) {
    //    if (elem == null)
    //        return;



    //    var successCallback = function (data, status, headers, config) {
    //        notificationFactory.success(data);
            
    //        $scope.carregarResLocal();
    //    };


    //    var errorCallback = function (data, status, headers, config) {
    //        notificationFactory.error(data);
    //    };

    //    responsavelFactory.updateResLocal(elem).success(successCallback).error(errorCallback);
    //};

    //$scope.apagarResLocal = function (elem) {
    //    if (elem == null)
    //        return;


    //    var successCallback = function (data, status, headers, config) {

    //        //$scope.carregarResLocal();
    //        notificationFactory.success(data);
    //        var arr = $scope.resLocal;
    //        for (i = 0; i < arr.length; i++) {
    //            if (arr[i] == elem) {
    //                arr.splice(i, 1);

    //                break;

    //            }
    //        }
    //        $scope.selectedResLocal = null;
    //    };


    //    var errorCallback = function (data, status, headers, config) {
    //        notificationFactory.error(data);
    //    };

    //    responsavelFactory.deleteResLocal(elem).success(successCallback).error(errorCallback);
    //};

    //$scope.confirmarApagarResLocal = function (row) {

    //    if (row == null)
    //        return;

    //    var modalInstance = $modal.open(
    //    {

    //        templateUrl: 'views/modalConfirmarApagar.html?v=' + new Date(),
    //        controller: 'modalController',
    //        resolve: {

    //            items: function () { return row; },

    //            //  isNew: false
    //        }
    //    });

    //    modalInstance.result.then(function (item) {

    //        $scope.apagarResLocal(item);

    //    }, function () {

    //    });

    //};

    //$scope.selResLocal = function (row) {
    //    $scope.selectedResLocal = row;
        
    //};



    //$scope.resLocalEditRow = function (row) {

    //    if (row == null) {
    //        row = {
    //            Pk_Local: 0,

    //            NomeLocal: "Nome",

    //            Fk_Responsavel: 0

    //        };

    //        row.op = "Novo";
    //    }
    //    else
    //        row.op = "Editar";

    //    var modalInstance = $modal.open(
    //    {

    //        templateUrl: 'views/modalEditarResLocal.html?v=' + new Date(),
    //        controller: 'modalController',
    //        resolve: {

    //            items: function () { return row; },

    //            //  isNew: false
    //        }
    //    });

    //    modalInstance.result.then(function (item) {
    //        if (item.op == "Editar")
    //        {
    //            $scope.selectedResLocal = item;
    //            $scope.updateResLocal(item);
    //        }
    //        else
    //        {
                
    //            $scope.inserirResLocal(item);
    //        }
            
    //    }, function () {

    //    });

    //};

   

    $scope.atribuirResponsavelCadastro = function (row, cadastro) {
        if (row == null || cadastro == null)
            return;
        
        $scope.selResponsavel(row);
        cadastro.NomeResponsavel = row.Nome;
        cadastro.Fk_Responsavel = row.Pk_Responsavel;
    };

    $scope.ativarLinhaResLocal = function (row, cadastro) {
        if (row == null || cadastro == null)
            return;
        if (row.Pk_Responsavel == cadastro.Fk_Responsavel) {
            $scope.selResponsavel(row);
            cadastro.NomeResponsavel = row.Nome;
            cadastro.Fk_Responsavel = row.Pk_Responsavel;
        }


    };

    $scope.showTabLocal = [];
    $scope.showTabLocal[0] = true;
    $scope.showTabLocal[1] = false;

    $scope.activarTabLocal = function (n) {
        $scope.showTabLocal[0] = false;
        $scope.showTabLocal[1] = false;
        $scope.showTabLocal[n] = true;
    };


    $scope.saveLogRGPD = function (row) {
        var getSuccessCallback = function (data, status) {
            $scope.editarResponsavel(row);

        };

        var errorCallback = function (data, status, headers, config) {

            notificationFactory.error(data);

        };

        var dados = $scope.selectedResponsavel;
        httpRequestFactory.postData('../api/responsavel/RGPD', dados).success(getSuccessCallback).error(errorCallback);

    };

    $scope.confirmarDadosSensiveis = function (row) {
        if (row == null)
            return;


        row.mensagem = "A janela que pretende aceder contêm dados pessoais. Deseja continuar?"


        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalConfirmar.html?v=' + new Date(),
            controller: 'modalController',
            resolve: {
                items: function () { return row; },
                //  isNew: false
            }
        });

        modalInstance.result.then(function (item) {
            $scope.saveLogRGPD(row);

        }, function () {

        });

    };

    $scope.isNumeric = function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

    $scope.openModalAssociarResponsavelUtilizador = function (row) {
                
        if (row == null) {
            notificationFactory.error("Indique o responsável");
            return;
        }
        
        if (row.IdUtilizador > 0 && row.Pk_Responsavel>0) {
            notificationFactory.error("Este responsável já tem um utilizador associado");
            return;
        }

        row.perm = $rootScope.perm_mnuUtilizadores;
        
        var modalInstance = $modal.open(
        {
            templateUrl: 'views/modalUtilizadores.html',
            controller: 'modalController',
            size: 'lg',
            resolve: {
                items: function () { return row; }
            }
        });

        modalInstance.result.then(function (item) {
            
            if (item == null) {
                notificationFactory.error("Não indicou o utilizador");
                return;
            }
            row.IdUtilizador = item.PK_Utilizador;
            row.Nome = item.Nome;
            if ($scope.selectedResponsavel != null) {
                $scope.selectedResponsavel.IdUtilizador = item.PK_Utilizador;
                $scope.selectedResponsavel.Nome = item.Nome;
            }
            
            //$scope.associaResponsavelAoUtilizador($scope.selectedResponsavel);
            
        }, function () {

        });
    };

    $scope.associaResponsavelAoUtilizador = function (dados) {
        var getSuccessCallback = function (data, status) {
            notificationFactory.success(data);
        };

        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);

        };
                
        httpRequestFactory.postData('../api/responsavel/utilizador/associa', dados).success(getSuccessCallback).error(errorCallback);

    };

  
});