Source: components/admin/controllers/representacao.controller.js

/**
 * @ngdoc controllers
 * @name Representacoes
 * @module s4c.components.admin.controllers.Representacoes
 *
 * @description
 * `AdminRepresentacoesCtrl` Controller da tela de Representação do módulo de administração
 * 
 * 
 */
(function () {
    'use strict';

    AdminRepresentacoesCtrl.$inject = [
        '$scope',
        '$http',
        '$mdDialog',
        'API_ENDPOINT',
        '$rootScope',
        'Usuario',
        'Base'
    ];

    var app = angular.module('s4c.controllers.AdminRepresentacoesCtrl', [

    ]).controller('AdminRepresentacoesCtrl', AdminRepresentacoesCtrl);

    app.filter('prettify', function () {

        function syntaxHighlight(json) {
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                var cls = 'number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'key';
                    } else {
                        cls = 'string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'boolean';
                } else if (/null/.test(match)) {
                    cls = 'null';
                }
                return '<span class="' + cls + '">' + match + '</span>';
            });
        }

        return syntaxHighlight;
    });

    app.directive('jsonText', function () {
        return {
            restrict: 'A', // only activate on element attribute
            require: 'ngModel', // get a hold of NgModelController
            link: function (scope, element, attrs, ngModelCtrl) {

                var lastValid;

                // push() if faster than unshift(), and avail. in IE8 and earlier (unshift isn't)
                ngModelCtrl.$parsers.push(fromUser);
                ngModelCtrl.$formatters.push(toUser);

                // clear any invalid changes on blur
                element.bind('blur', function () {
                    element.val(toUser(scope.$eval(attrs.ngModel)));
                });

                // $watch(attrs.ngModel) wouldn't work if this directive created a new scope;
                // see https://stackoverflow.com/questions/14693052/watch-ngmodel-from-inside-directive-using-isolate-scope how to do it then
                scope.$watch(attrs.ngModel, function (newValue, oldValue) {
                    lastValid = lastValid || newValue;

                    if (newValue != oldValue) {
                        ngModelCtrl.$setViewValue(toUser(newValue));

                        // TODO avoid this causing the focus of the input to be lost..
                        ngModelCtrl.$render();
                    }
                }, true); // MUST use objectEquality (true) here, for some reason..

                function fromUser(text) {
                    // Beware: trim() is not available in old browsers
                    if (!text || text.trim() === '') {
                        return {};
                    } else {
                        try {
                            lastValid = angular.fromJson(text);
                            ngModelCtrl.$setValidity('invalidJson', true);
                        } catch (e) {
                            ngModelCtrl.$setValidity('invalidJson', false);
                        }
                        return lastValid;
                    }
                }

                function toUser(object) {
                    // better than JSON.stringify(), because it formats + filters $$hashKey etc.
                    return angular.toJson(object, true);
                }
            }
        };
    });

    function AdminRepresentacoesCtrl($scope, $http, $mdDialog, API_ENDPOINT, $rootScope, Usuario, Base) {

        $scope.res = $rootScope.res;
        $scope.representacao = {};
        $scope.representacoesSelecionadas;
        $scope.representacoes;
        $scope.representacaoSelecionada;

        Base.obter('representacoes').then(function (reps) {
            $scope.representacoes = reps;
            $scope.representacoesSelecionadas = angular.copy($scope.representacoes);
        });

        /**
         * @method cancelar
         */
        function cancelar() {
            $scope.cancelado = true;
            $scope.isAdding = false;
            $scope.isEdition = false;
        }

        $scope.json;
        /**
         * @method selecionarRepresentacao
         * @param {*} representacao 
         */
        function selecionarRepresentacao(representacao) {

            if ($scope.isAdding || $scope.isEdition) {
                return;
            }

            $scope.representacaoSelecionada = representacao;

            if (!$scope.representacaoSelecionada.json) {
                Base.obter('representacoes/' + representacao.id).then(function (rep) {
                    $scope.representacaoSelecionada.json = rep.json;
                    $scope.json = JSON.stringify($scope.representacaoSelecionada.json, undefined, 4);
                    $scope.detalhes = true;
                });
            } else {
                $scope.json = JSON.stringify($scope.representacaoSelecionada.json, undefined, 4);
                $scope.detalhes = true;
            }
        }

        $scope.detalhes = false;
        $scope.cancelado = true;
        $scope.isAdding = false;
        $scope.isEdition = false;
        /**
         * @method novaRepresentacao
         * @param {*} event 
         */
        function novaRepresentacao(event) {
            $scope.cancelado = false;
            $scope.isAdding = true;
            $scope.isEdition = false;
            $scope.representacao = {};
        }


        $scope.usuarioSelecionado = undefined;
        /**
         * @method editarRepresentacao
         */
        function editarRepresentacao() {
            $scope.cancelado = false;
            $scope.isAdding = false;
            $scope.isEdition = true;
            $scope.representacao = angular.copy($scope.representacaoSelecionada);
        }

        /**
         * @method removerRepresentacao
         * 
         * @param {*} representacao 
         */
        function removerRepresentacao(representacao) {
            Base.remover('representacoes/' + representacao.id).then(function (rep) {

                if (!rep.id) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content($scope.res(rep.chave) + rep.valor)
                            .ok($scope.res('COMUM_OK')));
                    return;
                }

                var dialog = $mdDialog;
                dialog
                    .show(dialog.alert()
                        .title($scope.res('COMUM_SUCESSO'))
                        .content($scope.res('REPRESENTACAO_REMOVIDA'))
                        .ok($scope.res('COMUM_OK')));

                for (var index in $scope.representacoesSelecionadas) {
                    if ($scope.representacoesSelecionadas[index].id == rep.id) {
                        $scope.representacoesSelecionadas.splice(index, 1);
                        break;
                    }
                }

                for (var index in $scope.representacoes) {
                    if ($scope.representacoes[index].id == rep.id) {
                        $scope.representacoes.splice(index, 1);
                        break;
                    }
                }

                if ($scope.representacaoSelecionada && $scope.representacaoSelecionada.id == rep.id) {

                    $scope.representacaoSelecionada = undefined;
                    $scope.representacao = undefined;

                    $scope.detalhes = false;
                    $scope.isEdition = false;
                }
            });
        }

        /**
         * @method containsSameName
         */
        function containsSameName() {

            for (var index in $scope.representacoesSelecionadas) {
                if ($scope.representacoesSelecionadas[index].nome == $scope.representacao.nome
                    && $scope.representacoesSelecionadas[index].id != $scope.representacao.id) {
                    return true;
                }
            }

            return false;
        }

        /**
         * @method salvarRepresentacao
         */
        function salvarRepresentacao() {

            if (containsSameName()) {
                $mdDialog
                    .show($mdDialog.alert()
                        .title($scope.res('COMUM_ERRO'))
                        .content($scope.res('REPRESENTACAO_MESMO_NOME'))
                        .ok($scope.res('COMUM_OK')));
                return;
            }

            if (!$scope.representacao.nome) {
                $mdDialog
                    .show($mdDialog.alert()
                        .title($scope.res('COMUM_ERRO'))
                        .content($scope.res('ROTA_NOME_EHOBRIGATORIO'))
                        .ok($scope.res('COMUM_OK')));
                return;
            }

            if (!$scope.representacao.json) {
                $mdDialog
                    .show($mdDialog.alert()
                        .title($scope.res('COMUM_ERRO'))
                        .content($scope.res('REPRESENTACAO_JSON_OBRIGATORIO'))
                        .ok($scope.res('COMUM_OK')));
                return;
            }

            if ($scope.isAdding) {

                Base.salvar('representacoes', $scope.representacao).then(function (rep) {

                    if (!rep.id) {
                        $mdDialog
                            .show($mdDialog.alert()
                                .title($scope.res('COMUM_ERRO'))
                                .content($scope.res(u.Status))
                                .ok($scope.res('COMUM_OK')));
                        return;
                    }

                    $scope.representacao.id = rep.id;

                    //Tem que adicionar nas duas listas. 
                    $scope.representacoes.push($scope.representacao);
                    $scope.representacoesSelecionadas.push($scope.representacao);

                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_SUCESSO'))
                            .content($scope.res('REPRESENTACAO_SALVA'))
                            .ok($scope.res('COMUM_OK')));

                    selecionarRepresentacao($scope.representacao);
                    $scope.isAdding = false;
                    $scope.cancelado = true;

                });

            } else if ($scope.isEdition) {

                Base.atualizar('representacoes', $scope.representacao).then(function (rep) {

                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_SUCESSO'))
                            .content($scope.res('REPRESENTACAO_ATUALIZADA'))
                            .ok($scope.res('COMUM_OK')));

                    //Não remover este código. Nome do usuário não é atualizado na lista sem ele.
                    for (var index in $scope.representacoesSelecionadas) {
                        if ($scope.representacoesSelecionadas[index].id == $scope.representacao.id) {
                            $scope.representacoesSelecionadas.splice(index, 1);
                            break;
                        }
                    }

                    for (var index in $scope.representacoes) {
                        if ($scope.representacoes[index].id == $scope.representacao.id) {
                            $scope.representacoes.splice(index, 1);
                            break;
                        }
                    }

                    $scope.representacaoSelecionada = $scope.representacao;
                    $scope.representacoesSelecionadas.push($scope.representacaoSelecionada);
                    $scope.representacoes.push($scope.representacaoSelecionada);
                    $scope.json = JSON.stringify($scope.representacaoSelecionada.json, undefined, 4);

                    selecionarRepresentacao($scope.representacao);
                    $scope.isEdition = false;
                    $scope.cancelado = true;

                });
            }
        }

        $scope.textoBusca;
        /**
         * @method executeSearch
         * @param {*} e 
         */
        function executeSearch(e) {
            $scope.representacoesSelecionadas = [];
            var texto = $scope.textoBusca.toLowerCase();
            angular.forEach($scope.representacoes, function (rep) {

                var nome = rep.nome.toLowerCase();

                if (nome.indexOf(texto) !== -1) {
                    $scope.representacoesSelecionadas.push(rep);
                }
            });
        }

        angular.extend($scope, {
            cancelar: cancelar,
            novaRepresentacao: novaRepresentacao,
            editarRepresentacao: editarRepresentacao,
            removerRepresentacao: removerRepresentacao,
            executeSearch: executeSearch,
            selecionarRepresentacao: selecionarRepresentacao,
            salvarRepresentacao: salvarRepresentacao
        });

    }

}());