// Controller for the Widget.
var controller = (function($) {
	
	var attributes,	audioUrl, currentIndex = 0,			
		wwClient = qmatic.webwidget.client,
		attributeKeys = {
			
		},
		attributeDefaults = {};

    var intervalId = null;

	var currentTicketNumber = 100;
	
	var preDefTemplates = [
		{
			name : 'Visit Call',
			topic : 'com.qmatic.qp.topic.event.VISIT_CALL',
            template : '{"evnt":"VISIT_CALL","type":"DEVICE","ts":"2013-06-10T14:01:03.474+0200","did":130106600001,"prm":{"branchId":1,"confirmNeeded":false,"eventTime":"2013-06-10T14:01:03.091+0200","isConfirmed":false,"isLeft":false,"isRight":false,"queueId":110000000001,"queueName":"Default Queue","service":1,"serviceOrigId":1,"servicePointId":120000000001,"servicePointLogicId":1,"servicePointName":"Web service point 1","ticket":"{{ticketNumber}}","totWaitTime":22,"visitId":2,"waitingTime":22}}'
		},
		{
			name : 'Visit End',
			topic : 'com.qmatic.qp.topic.event.VISIT_END',
            template : '{"evnt":"VISIT_END","SRC":"CFM","DT":"20120608151046","uid":10020001,"prm":{"queue":10100001,"ticket":"{{ticketNumber}}"}}'
		},
		{
			name : 'Service point open',
			topic : 'com.qmatic.qp.topic.event.SERVICE_POINT_OPEN',
            template : '{"evnt":"SERVICE_POINT_OPEN","SRC":"CFM","DT":"20120608151046","uid":10020001,"prm":{"queue":10100001,"ticket":"{{ticketNumber}}"}}'
		},
		{
			name : 'Service point close',
			topic : 'com.qmatic.qp.topic.event.SERVICE_POINT_CLOSE',
            template : '{"evnt":"SERVICE_POINT_CLOSE","SRC":"CFM","DT":"20120608151046","uid":10020001,"prm":{"queue":10100001,"ticket":"{{ticketNumber}}"}}'
		}
	];
	
	var fireEvent = function(interval) {
		console.log("ENTER - fireEvent");

        if(intervalId != null) {
            clearInterval(intervalId);
        }
		intervalId = setInterval(function() {
            var template = preDefTemplates[currentIndex].template.replace('{{ticketNumber}}', currentTicketNumber++);
            template = template.replace('{{branchId}}', wwClient.getBranchId());
            template = template.replace('{{unitId}}', wwClient.getUnitId());

            wwClient.publish(preDefTemplates[currentIndex].topic, JSON.parse(template));
            console.log("Published event: " + preDefTemplates[currentIndex].topic + " Payload: " + template);

        }, interval);
	};
	
	// Public contents of controller
	return {
		/**
		 * Called when widget client has finished loading. This is where you initialize your widget
		 */
		onLoaded : function(configuration) {
			var attr = configuration.attributes;
			
			var attribParser = new qmatic.webwidget.AttributeParser(attr || {}),
				defaultsParser = new qmatic.webwidget.AttributeParser(attributeDefaults),
				ak = attributeKeys;				
						
			attributes = attr;
			
			
			
			$( "#play" ).button({
				text: false,
				icons: {
					primary: "ui-icon-play"
				}
			}).click(function() {
				// Start publishing events
				var interval = $("input[name=repeat]:checked").val();
				console.log("Current timeout: " + interval);
				currentIndex = $('#event').val();
				fireEvent(interval);
				
			});
			$( "#stop" ).button({
				text: false,
				icons: {
					primary: "ui-icon-stop"
				}
			}).click(function() {
                    if(intervalId != null) {
                        clearInterval(intervalId);
                    }
			});
			
			$( "#repeat" ).buttonset();
			
			$('#event').empty();
			for(var i = 0; i < preDefTemplates.length; i++) {
				$('#event').append(new Option(preDefTemplates[i].name, i));
			}
			
			
			$( "#configure" ).button({
				text: true,
				icons: {
					primary: "ui-icon-clipboard"
				}
			}).click(function() {
				$('#dialog').dialog("open");
				currentIndex = $('#event').val();
				$('#dialog').dialog({'title': preDefTemplates[currentIndex].name});
				$('#dialog').find('textarea').val(preDefTemplates[currentIndex].template);
			});
			
			
			$( "#dialog" ).dialog({
				autoOpen: false,
				height: 300,
				width: 350,
				modal: true,
				buttons: {
					"Ok": function() {
						preDefTemplates[currentIndex].template = $('#dialog textarea').val();
						$( this ).dialog( "close" );
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					
				}
			});
			
			// Add event subscriptions here
		},
		
		onLoadError : function(message) {
			$('body').append('<p>Widget load error: ' + message + '</p>');
		}
	};	
	
})(jQuery);