

app.factory('loginFactory', function (Base64, $http, $window, $location) {
    var urlogin = '../api/login/';
    return {
        /** BASIC AUTH HEADERS **/
        setCredentials: function (username, password) {
            
            var encoded = Base64.encode(username + ':' + password);
            
            $http.defaults.headers.common.Authorization = 'Basic ' + encoded;
            return $http.get(urlogin);
        },

        validCredentials: function (id,enctoken) {
            
            $window.sessionStorage.setItem('token', $http.defaults.headers.common['Authorization']);
            $window.sessionStorage.setItem('id.cibe.inovar', id);
            $window.sessionStorage.setItem('enctoken.cibe.inovar', enctoken);
            $location.path("/cadastro");
        },

        clearCredentials: function () {
            $window.sessionStorage.removeItem('token');
            $window.sessionStorage.removeItem('id.cibe.inovar');
            $window.sessionStorage.removeItem('enctoken.cibe.inovar');
            $window.sessionStorage.removeItem('perfilSelect');
            $window.sessionStorage.removeItem('username.cibe.inovar');
            $window.sessionStorage.removeItem('tipout.cibe.inovar');
            $window.sessionStorage.removeItem('CibeAtk');
            $window.sessionStorage.removeItem('CibeUltimaEntradaStr');
            $window.sessionStorage.removeItem('CibeUsernameAlt');
            $window.sessionStorage.removeItem('usaProgContabilidade');
            $http.defaults.headers.common['Authorization'] = "";
        },
        encerrar: function () {
            $http({
                method: 'GET',
                url: '../api/logout',
                headers: {
                    'Content-Type': 'application/json',
                    'Atk': $window.sessionStorage.getItem('CibeAtk')
                }
            })

            this.clearCredentials();
        },
        encerrarSessao:function() {
            this.encerrar();

            $location.path("/login");
        },
        encerrarSessaoRedirect: function (url) {
            this.encerrar();

            $location.href(url);
        },

       

        
    };
});