(function () {
    "use strict";

    angular.module('pos').controller('usuarioController', controller);
    controller.$inject = ['$scope', '$window', '$timeout', 'usuarioService', 'vendedorService', '$state'];

    function controller($scope, $window, $timeout, usuarioService, vendedorService, $state) {

        $scope.state = { data: [], filtro: { ativo: false, nome: "" } };

        $scope.initialize = function () {
            $scope.refresh();
            redirect();
        }
        $scope.refresh = function () {
            $scope.getAll();
        }
        $scope.toggleFilter = function () {
            $scope.state.filtro.ativo = !$scope.state.filtro.ativo;
        }

        $scope.filterByName = function (item) {
            return item.Nome.toUpperCase().indexOf($scope.state.filtro.nome.toUpperCase()) >= 0 || $scope.state.filtro.nome == "" || item.selecionado;
        };

        var redirect = function () {
            if (!$scope.$parent.environment.perfil.IndicaGerente)
                $state.go('state-usuario-detail', { codigo: $scope.$parent.environment.perfil.Codigo })
        }
        $scope.getAll = function () {
            $scope.state.carregando = true;
            $scope.state.vazio = true;

            vendedorService
                .getAll()
                .then(
                    function (response) {
                        $scope.state.carregando = false;

                        if (response.Status < 0)
                            $scope.$parent.toastr.error(response.Message, 'Serviço');
                        else
                            angular.copy(angular.fromJson(response.Data), $scope.state.data);

                        $scope.state.vazio = !(response.Data && response.Data.length > 0);
                    },
                    function (err) { $scope.$parent.toastr.error(err); }
                );
        };

        $scope.historyBack = function () {
            $window.history.back();
        }

        $scope.clearFilter = function () {
            $scope.state.filtro.nome = "";
        }


        $scope.initialize();
    }

})();