'use strict';

var server           = require('mano/lib/client/server-sync')
  , isReadOnlyRender = require('mano/client/utils/is-read-only-render')
  , delay            = require('timers-ext/delay');

var reload = function () {
	localStorage._reload = '1';
	window.location.href = '/';
};

module.exports = function (user) {
	var inReload;
	if (isReadOnlyRender) return;
	// Delay response, as immediate reloads were observed, and they got to server
	// before it had new app resolved
	user._appAccessId.on('change', delay(function (event) {
		if (inReload) {
			console.log("App access id change ", event.oldValue, " -> ", event.newValue, ", ignored");
			return;
		}
		inReload = true;
		if (server.isSync) {
			console.log("App access id change ", event.oldValue, " -> ", event.newValue, ", immediate");
			reload();
		} else {
			console.log("App access id change ", event.oldValue, " -> ", event.newValue,
				", wait for sync");
			server.once('sync', function () {
				console.log("App access id: reload after sync");
				reload();
			});
		}
	}, 100));
	user._appName.on('change', delay(function (event) {
		if (inReload) {
			console.log("App name change ", event.oldValue, " -> ", event.newValue, ", ignored");
			return;
		}
		inReload = true;
		if (server.isSync) {
			console.log("App name change ", event.oldValue, " -> ", event.newValue, ", immediate");
			reload();
		} else {
			console.log("App name change ", event.oldValue, " -> ", event.newValue,
				", wait for sync");
			server.once('sync', function () {
				console.log("App name: reload after sync");
				reload();
			});
		}
	}, 100));
};

@@ -479,16 +479,111 @@
 esolved%0A
+%09// Proper fix would be to send static version from server (so we're never faster then server)%0A
 %09user._a
@@ -623,32 +623,32 @@
 ction (event) %7B%0A
-
 %09%09if (inReload) 
@@ -1139,25 +1139,25 @@
 %7D);%0A%09%09%7D%0A%09%7D, 
-1
+3
 00));%0A%09user.
@@ -1695,17 +1695,17 @@
 %09%09%7D%0A%09%7D, 
-1
+3
 00));%0A%7D;

Increase app switch timeout