'use strict';

angular.module('sbAdminApp').factory('LoginSession', function ($http, Storage) {
    var authService = {};

    authService.login = function (credentials) {
        return $http
            .post('/login', credentials)
            .then(function (res) {
            Session.create(res.data.id, res.data.user.id, res.data.user.role);
            return res.data.user;
        });
    };

    authService.isAuthenticated = function () {
        return !!Session.userId;
    };

    authService.isAuthorized = function (authorizedRoles) {
        if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
        }
        return (authService.isAuthenticated() && authorizedRoles.indexOf(Session.userRole) !== -1);
    };

    authService.expire = function() {
        Session.userId = '';
    }

    return authService;
})

angular.module('sbAdminApp').factory('AuthService', function ($http, LoginSession) {
    var authService = {
        user: {
            id: '',
            name: '',
            role: '',
            token: '',
            expire: 0
        }
    };

    authService.login = function (credentials) {
        return $http
            .post('/login', credentials)
            .then(function (res) {
            return user.id;
        });
    };

    authService.isAuthenticated = function () {
        return !!LoginSession.userId;
    };

    authService.isAuthorized = function (authorizedRoles) {
        if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
        }
        return (authService.isAuthenticated() && authorizedRoles.indexOf(LoginSession.userRole) !== -1);
    };

    authService.expire = function() {
        LoginSession.userId = '';
    }

    return authService;
})