(function() {
    'use strict';

    angular
        .module('app-base')
        .service('FireBase',FireBase);

    /** @ngInject */
    function FireBase($q,$log,$rootScope,$firebaseObject,$firebaseAuth,$window) {
        var _this = this;
        this.fbs = {};

        this.init = function(uri){
            var deferred = $q.defer();
            var ref = new $window.Firebase(uri);
            var db = $firebaseObject(ref);
            var auth = $firebaseAuth(ref);
            auth.$onAuth(function(authData) {
                _this.fbs[uri].authData = authData;
                $rootScope.$broadcast('firebase-user-state-change',authData);
            });
            _this.fbs[uri] = {db:db,ref:ref,auth:auth};

            db.$loaded().then(function() {
                deferred.resolve(_this.fbs[uri]);
            });
            return deferred.promise;
        };
        this.save = function(db){
            db.$save().then(function(){
                $log.log('db saved');
            });
        };
        this.authWithPassword = function (userObj,fbObj) {
            var deferred = $q.defer();
            var auth = fbObj.auth;
            auth.$authWithPassword(userObj).then(function(authData) {
                $log.log("Logged in as: "+ authData.uid);
                deferred.resolve(authData);
            }).catch(function(error) {
                $log.error("Authentication failed:", error);
                deferred.reject(error);
            });
            return deferred.promise;
        };
        this.createUser = function(userObj,fbObj) {
            var deferred = $q.defer();
            var auth = fbObj.auth;
            auth.$createUser({
                email: userObj.email,
                password: userObj.password
            }).then(function(authData) {
                $log.log( "User created with uid: " + authData.uid);
                deferred.resolve(authData);
            }).catch(function(error) {
                $log.error('error creating user',error);
                deferred.reject(error);
            });
        };
        this.createUserAndLogin = function (userObj,fbObj) {
            var _this = this;
            return this.createUser(userObj,fbObj).then(function () {
                    return _this.authWithPassword(userObj,fbObj);
                });
        };
        this.logoutUser = function(fbObj){
            var auth = fbObj.auth;
            auth.$unauth();
        };
    }
})();


