var app = app || {};
var GW_BUSY_TIME = 5000;

var Touchlink = (function () {
	var tl = {};

	return tl;
}());

/**
 * Model which represents a single node in the touchlink list.
 */
app.TouchlinkNode = Backbone.Model.extend({
	defaults: {
		name: 'unknown',
		factoryNew: false
	},
	initialize: function() {
		this.on('change', function() {
			console.log('change event');
		});
	},

	// send identify command to the node
	identify: function() {

		$.post('/api/' + apikey + '/touchlink/' + this.id + '/identify', function(data) {
  			clearAlert();
			showAlert('alert-info', '<b>OK!</b> Command send. Please wait a few seconds', '#touchlink-alerts');
			setTimeout(function(){$('.ide').addClass("identify");$('.ide').removeClass("disabled");$('.res').addClass("reset");$('.res').removeClass("disabled");$('.btn-scan').attr("id","btn-scan");$('.btn-scan').removeClass("disabled");showAlert('alert-success', '<b> OK!</b> Touchlink ready', '#touchlink-alerts')},GW_BUSY_TIME);
		})
		.fail(function(jqXHR, textStatus, errorThrown) {
			// temporary busy
			$('.ide').addClass("disabled");
			$('.ide').removeClass("identify");
			
			$('.res').addClass("disabled");
			$('.res').removeClass("reset");

			$('.btn-scan').addClass("disabled");
			$('.btn-scan').removeAttr("id");
			
			if (jqXHR.status === 503) { // Service Unavailable
				showAlert('alert-warning', '<b>Busy!</b> Please try again in a few seconds.', '#touchlink-alerts');
				setTimeout(function(){$('.ide').addClass("identify");$('.ide').removeClass("disabled");$('.res').addClass("reset");$('.res').removeClass("disabled");$('.btn-scan').attr("id","btn-scan");$('.btn-scan').removeClass("disabled");showAlert('alert-success', '<b> OK!</b> Touchlink ready', '#touchlink-alerts')},GW_BUSY_TIME);
			}
		});
	},
	// send reset to factory new command to the node
	resetToFactoryNew: function() {
		deleteScenesOfLight(this.attributes.address);
		$.post('/api/' + apikey + '/touchlink/' + this.id + '/reset', function(data) {
			clearAlert();
			showAlert('alert-info', '<b>OK!</b> Reset to factory new command send. Please wait a few seconds', '#touchlink-alerts');
			setTimeout(function(){$('.ide').addClass("identify");$('.ide').removeClass("disabled");$('.res').addClass("reset");$('.res').removeClass("disabled");$('.btn-scan').attr("id","btn-scan");$('.btn-scan').removeClass("disabled");showAlert('alert-success', '<b> OK!</b> Touchlink ready', '#touchlink-alerts')},GW_BUSY_TIME);
		})
		.fail(function(jqXHR, textStatus, errorThrown) {
			// temporary busy
			$('.ide').addClass("disabled");
			$('.ide').removeClass("identify");
			
			$('.res').addClass("disabled");
			$('.res').removeClass("reset");
			
			$('.btn-scan').addClass("disabled");
			$('.btn-scan').removeAttr("id");
			
			if (jqXHR.status === 503) { // Service Unavailable
				showAlert('alert-warning', '<b>Busy!</b> Please try again in a few seconds.', '#touchlink-alerts');
				setTimeout(function(){$('.ide').addClass("identify");$('.ide').removeClass("disabled");$('.res').addClass("reset");$('.res').removeClass("disabled");$('.btn-scan').attr("id","btn-scan");$('.btn-scan').removeClass("disabled");showAlert('alert-success', '<b> OK!</b> Touchlink ready', '#touchlink-alerts')},GW_BUSY_TIME);
			}
		});
	}
});

/**
 * Callback then scan results are received.
 */
function fetchScanResultSuccess(collection, response, options) {

	// reset and hide progress bar
	$('#scanProgressBar').css('display', 'none');
	$('#scanProgressBar .bar').css('width', '0%');
	$('.node-list-head').removeClass('hidden');
	$('.btn-scan').attr("id","btn-scan");
	
	if (collection.length === 0) {
		showAlert('alert-warning', '<b>Note!</b> No lights where found. Please try again and make sure the lights are close enough to the gateway.', '#touchlink-alerts');
	}
	else {
		showAlert('alert-success', '<b>OK!</b> Found ' + collection.length + ((collection.length === 1) ? ' light' : ' lights') + '.', '#touchlink-alerts');
	}
}

/**
 * Collection for the nodes found by a touchlink scan reqeuest.
 */
var TouchlinkNodeCollection = Backbone.Collection.extend({
	model: app.TouchlinkNode,
	url: function() {
		return '/api/' + apikey + '/touchlink/scan';
	},

	parse: function(response, options) {
    	// prepare scan results to show
		var arr = [];
		
		_.each(response.result, function(item, index) {
			var panid = item.panid.toString(16);
				if (panid.length >= 4) {
					panid = "0x" + panid;
				} else if (panid.length > 2 && panid.length < 4) {
					panid = "0x0" + panid;
				} else if (panid.length > 1 && panid.length < 3) {
					panid = "0x00" + panid;
				} else if (panid.length > 0 && panid.length < 2) {
					panid = "0x000" + panid;
				} else {
					panid = "0x0000";
				}
		
			var node = {
				id: index,
				factoryNew: item.factoryNew,
				name: item.name || 'Light ' + index,
				address: item.address,
                rssi: item.rssi,
                channel: item.channel,
                panid: panid
			};
			arr.push(node);
		});

		if (arr.length > 0) {
			$('.node-list-head').removeClass('hidden');
		}
		
		return arr;
	}
});

/**
 * View for a single touchlink node.
 */
app.TouchlinkNodeView = Backbone.View.extend({
	tagName: 'tr',

	// cache the template function for a single view
	template: _.template($('#tl-item-template').html()),

	initialize: function() {
		this.listenTo(this.model, 'change', this.render);
	},

	// DOM events specific to an item
	events: {
		'click .identify': 'identify',
		'click .reset': 'resetToFactoryNew'//,
		//'click .node-name': 'extendView'
	},

	render: function() {
		this.$el.html(this.template(this.model.toJSON()));
		this.$identify = this.$('.identify');
		this.$reset = this.$('.reset');
		this.$extend = this.$('.node-name');
		return this;
	},

	identify: function() {
		this.model.identify();
	},

	resetToFactoryNew: function() {
		this.model.resetToFactoryNew();
	},
	
	//extendView: function() {
    //    $('.node-extended').toggleClass('hidden');
	//}
});

/**
 * View which to control touchlink commands and show scan results.
 */
app.TouchlinkView = Backbone.View.extend({
	el: '#touchlink-view',

	initialize: function() {
		this.$scan = this.$('#btn-scan');
		this.listenTo(app.TouchlinkNodes, 'add', this.addOne);
		this.listenTo(app.TouchlinkNodes, 'reset', this.render);
	},

	events: {
		'click #btn-scan': 'scan',
		'click #btn-done': 'backToMain'
	},

	render: function() {
		this.$('#node-list tbody').html('');
		app.TouchlinkNodes.each(this.addOne, this);
	},

	addOne: function(node) {
		var view = new app.TouchlinkNodeView({ model: node });
		$('#node-list tbody').append(view.render().el);
	},

	scan: function() {
		var duration = 11000; // ms
		var updateInterval = 250; // ms
		var percent = 0;
		var $bar = $('#scanProgressBar .bar')[0];
		clearAlert();
		$('.btn-scan').removeAttr("id");
		
		// updates the progress bar and fetches the scan results at 100%
		var updatefn = function() {
			if (percent < 100) {
				percent += Math.abs(100 / (duration / updateInterval));
			}

			$bar.style.width = (percent % 100) + '%';

			if (percent >= 100) {
				app.TouchlinkNodes.fetch({
					success: fetchScanResultSuccess
				});
			}
			else {
				setTimeout(updatefn, updateInterval)
			}
		};

		$.post('/api/' + apikey + '/touchlink/scan', function(data) {

			$('#node-list tbody').html('');
			$('.node-list-head').addClass('hidden');
			app.TouchlinkNodes.reset();

  			showAlert('alert-info', '<b>OK!</b> Scanning started ...', '#touchlink-alerts');
  			
  			// show the scan progress bar
  			$bar.style.width = percent + '%';
  			$('#scanProgressBar').css('display', 'block');

  			// call progress bar update function
  			setTimeout(updatefn, updateInterval);
		})
		.fail(function(jqXHR, textStatus, errorThrown) {
			
			// temporary busy
			$('.ide').addClass("disabled");
			$('.ide').removeClass("identify");
			
			$('.res').addClass("disabled");
			$('.res').removeClass("reset");

			$('.btn-scan').addClass("disabled");
			$('.btn-scan').removeAttr("id");
			
			if (jqXHR.status === 503) { // Service Unavailable
				showAlert('alert-warning', '<b>Busy!</b> Please try again in a few seconds.', '#touchlink-alerts');
				setTimeout(function(){$('.ide').addClass("identify");$('.ide').removeClass("disabled");$('.res').addClass("reset");$('.res').removeClass("disabled");$('.btn-scan').attr("id","btn-scan");$('.btn-scan').removeClass("disabled");showAlert('alert-success', '<b> OK!</b> Touchlink ready', '#touchlink-alerts')},GW_BUSY_TIME);
			}
		});
	},

	backToMain: function() {
		window.location.assign("/");
	}
});

$(document).ready(function() {
    initBranding();
    // init fastclick
    FastClick.attach(document.body);

    // prevent default sending of form
    $('form').submit(function(e){
        e.preventDefault();
        return false;
    });

	app.TouchlinkNodes = new TouchlinkNodeCollection();
	new app.TouchlinkView();

	// there might be previous results
	app.TouchlinkNodes.fetch();
});
