'use strict';

var Multiplayer = (function(){

	var localPlayer = {};
	var playersRef = null;
	var playerRef = null;
	var userId = null

	// anonymous auth
	function Auth() {
		firebase.auth().signInAnonymously().catch(function(error) {
			var errorCode = error.code;
			var errorMessage = error.message;
		});

		firebase.auth().onAuthStateChanged(function(loggedUser) {
			if (loggedUser) {
				userId = loggedUser.uid;

				InitRefs(userId);
			}
		});
	}

	function Init() {
		firebase.initializeApp({
			apiKey: 'AIzaSyBHIgdw94zjXqGSBbVJs5QvjU_X6LFxb_k',
			authDomain: 'prague-castle.firebaseapp.com',
			databaseURL: 'https://prague-castle.firebaseio.com',
			storageBucket: 'prague-castle.appspot.com',
			messagingSenderId: '505903385814'
		});

		Auth();
	}

	function InitRefs(userId) {
		playersRef = firebase.database().ref('/players');
		playerRef = playersRef.child(userId);

		playersRef.remove(); // clear unreferenced nodes - probably Firebase bug when anonymous auth used
		playersRef.on('value', OnPlayersValue);
		playersRef.on('child_removed', OnPlayerRemoved)
		playerRef.onDisconnect().remove();
	}

	function OnPlayerRemoved(data) {
		castleScene.removeObject(data.key);
	};

	function OnPlayersValue(snapshot) {
		if (Preferences.Multiplayer.SHOW_USERS) {
			snapshot.forEach(function (other) {
				if (other.key != localPlayer.key) {
					castleScene.updateOrAdd(other.key, other.val().position);
				}
			});
		} else {
			snapshot.forEach(function (other) {
				if (other.key != localPlayer.key) {
					castleScene.removeObject(other.key);
				}
			});
		}
	}

	function Update(cameraPosition) {
		if(!playerRef) {
			return;
		}

		playerRef.update({
			position: {
				x: cameraPosition.x,
				y: cameraPosition.y,
				z: cameraPosition.z,
			},
			timestamp: firebase.database.ServerValue.TIMESTAMP
		});
	}

	return {
		Init: Init,
		Update: Update,
	}
})();
