 App = require 'app'
 Plugin = require 'plugin'
 
+BUFFER_TIME = 1000
+
 exports.render = ->
-	###
 	# create local copy of the scores
 	localScores = Obs.create {}
+	copied = {}
 	Obs.observe !->
 		Db.shared.iterate 'counters', (v) !->
+			# just copy once!
+			return if copied[v.key()]
+			copied[v.key()] = true
 			localScores.set 'counters', v.key(), v.peek()
 
-	done = Obs.create true
+	buffer = Obs.create 0
+	# keep app user's local score synced with buffer
 	Obs.observe !->
-		diff = player.get('score') - localPlayer.peek('score')
-		return if diff is 0
-		done.set false
-		setInterval (1/diff), !->
-			localPlayer.incr 'score'
-			if player.get('score') is localPlayer.peek('score') done.set true
-	###
-	buffer = Obs.create 0
+		newVal = Db.shared.get('counters', App.userId()) + buffer.get()
+		localScores.set 'counters', App.userId(), newVal
 
 	Ui.card !->
 		renderButton buffer
 
 		renderFunny()
 
-	renderScores buffer
+	renderScores localScores
 
 renderButton = (buffer) !->
 	buffering = Obs.create false

		if funny?
			Dom.div !->
				Dom.animate
            			create:
            				opacity: 1 # target
            				initial:
                  				opacity: 0
            			remove:
            				opacity: 0 # target
            				initial:
                  				opacity: 1
            			content: !->
						Dom.style fontSize: '150%', textAlign: 'center', padding: "30px 5px 15px"
						Dom.text funny

renderScores = (buffer) !->
	Ui.list !->
		Dom.style margin: '0 15px'
		Db.shared.iterate 'counters',
			((counter) !-> renderScore(counter, buffer)),
			(counter) -> -(counter.get() + if (counter.key() is App.userId()) then buffer.get() else 0)

renderScore = (counter, buffer) !->
	Ui.item !->
		userId = +counter.key()
		if userId is App.userId()


	Obs.observe !->
		return unless buffering.get()
		Obs.onTime BUFFER_TIME, !->
			bufferedClicks = buffer.peek()
			buffer.set(0)

