///<reference path=".#ts/client.d.ts" />

interface Templates {
	notifications: Template;
}

var notificationBetsSub: any = null;
Tracker.autorun(function(){
	var betIds = Session.get('notificationBets') || [];
	if (!betIds.length) {
		if (notificationBetsSub) {
			notificationBetsSub.stop();
		}
		return;
	}
	notificationBetsSub = Meteor.subscribe('betting/BetAlt', {_id: {$in: betIds}});
});

Template.notifications.helpers({

	howlNotifications: function () {

		return Notifications.NotificationClient.db.find({'options.config.type': {$ne: Notifications.Type.TEMPLATE}})
			.fetch().filter((x: Notifications.NotificationClient) => x.isVisible());
	},

	templateNotifications: function () {
		return Notifications.Notification.db.find({'options.config.type': Notifications.Type.TEMPLATE})
			.fetch().filter((x: Notifications.NotificationClient) => x.isVisible());
	}

});

Template.notifications.events({

	'click .close': function () {
		this.setRead();
	},

	'click .howl-message': function () {
		if (this.options.content.href && this.options.content.href != 'depositReceived') {
			document.location.href = this.options.content.href;
		}
		this.setRead();
	}

});

Template.notifications.onRendered(function () {

	this.subscribe('SiteNotifications', {'options.config.visible': true});

	this.autorun(() => {
		if (Meteor.user()) {
			this.subscribe('UserNotifications');
		}

		Notifications.Notification.db.find().observeChanges({
			added: function (id, fields) {
				Notifications.timedNotification(id, fields);
			},
			changed: function (id, fields) {
				Notifications.timedNotification(id, fields);
			},
			removed: function (id) {
				Notifications.removeNotification(id);
			}
		});
	});
});
