app.factory('loginFactory', ['$http', '$q','$rootScope','AUTH_EVENTS' ,'$location','$cookieStore', function ($http,$q,$rootScope,AUTH_EVENTS,$location,$cookieStore) {
    var loginData = {};

    loginData.login = function(credentials) {
        var $promise = $http.post('/login', credentials); //send data to server.py
        $promise.then(function(msg) {
        	console.log(msg);
            if (msg.data == 'success') {
                $rootScope.AUTH_EVENTS = AUTH_EVENTS.loginSuccess;
                $cookieStore.put(AUTH_EVENTS, AUTH_EVENTS.loginSuccess);
                $location.path('/dashboard');
            } else {
                $rootScope.AUTH_EVENTS = AUTH_EVENTS.loginFailed;
                scope.errormessage.isError = true;
                scope.errormessage.msg = "Wrong username and password";
                console.log("failed 1");
            }
        }, function() {
            $rootScope.AUTH_EVENTS = AUTH_EVENTS.loginFailed;
            console.log("failed 2");
        });
    }
    return loginData;
}])
