interface Templates {
	sportsLive: Template;
}

Template.sportsLive.onCreated(function() {
	disableSite();
	Session.set('liveDataLimit', 10);
});

Template.sportsLive.onRendered(function() {

	if (Session.get('liveDataLimit') === 10) {
		this.autorun(() => {
			var selector = {
				live: true,
				matchStatus: {$nin: Betting.nonLiveStatuses}
			};
			Meteor.call('betting/Event/total', selector, (err, data) => {
				if (!err) {
					Session.set('liveEventCount', data);
				}
			});
		});
	}

	$('#content').scroll(() => {
		var threshold, target = $('#showMoreLiveResults');
		if (!target.length) {
			return;
		}

		threshold = $(window).scrollTop() + $(window).height() - target.height() + 100;
		if (target.offset().top <= threshold) {
			if (!target.data('visible')) {
				target.data('visible', true);
				Session.set('liveDataLimit', Session.get('liveDataLimit') + 10);
				let selector = {
					live: true,
					matchStatus: {$nin: Betting.nonLiveStatuses},
				};
				let options = <any>{sort: {startTime: 1}, limit: Session.get('liveDataLimit'), skip: 10};
				let sub = this.subscribe('betting/Event', _.extend({mainCategoryRoot: {$ne: null}}, selector), options, ['mainCategoryPath', 'competition']);
				if (!sub.ready()) {
					return;
				}

				var events = Betting.Event.db.find(selector, _.extend({fields: {mainCategoryPath: 1}}, options)).fetch();
				var eventIds = events.map(x => x._id);
				var marketTypes = _.uniq(events.reduce((all, cur) => all.concat(cur.listLiveMarketTypeIds()), []));

				var sel = {type: {$in: marketTypes}, event: {$in: eventIds}};
				this.subscribe('betting/Market', sel);
				this.subscribe('betting/Selection', sel);
			}
		} else {
			if (target.data('visible')) {
				target.data('visible', false);
			}
		}
	});

	this.autorun(() => {
		let selector = {
			live: true,
			matchStatus: {$nin: Betting.nonLiveStatuses},
		};
		let options = <any>{sort: {startTime: 1}, limit: 10};
		let sub = this.subscribe('betting/Event', _.extend({mainCategoryRoot: {$ne: null}}, selector), options, ['mainCategoryPath', 'competition']);
		if (!sub.ready()) {
			return;
		}

		var events = Betting.Event.db.find(selector, _.extend({fields: {mainCategoryPath: 1}}, options)).fetch();
		var eventIds = events.map(x => x._id);
		var marketTypes = _.uniq(events.reduce((all, cur) => all.concat(cur.listLiveMarketTypeIds()), []));

		var sel = {type: {$in: marketTypes}, event: {$in: eventIds}};
		this.subscribe('betting/Market', sel);
		this.subscribe('betting/Selection', sel);
		enableSite();
	});
	Session.set('firstLoad', true);
});

Template.sportsLive.helpers({

	loading: function() {
		// So that the loading wouldn't trigger every time infinite scroll is triggered
		if (Session.get('firstLoad')) {
			return false;
		}
		var tpl = Template.instance();
		if (tpl.subscriptionsReady()) {
			return false;
		}
		return true;
	},

	events: function() {
		return <any>Betting.Event.db.find({
			live: true,
			$or: [{active: true}, {matchStatus: {$nin: Betting.nonLiveStatuses}}],
		}, {sort: {startTime: 1, name: 1}});
	},

	eventCount: function() {
		return Betting.Event.db.find().count();
	},

	totalUpcomingEvents: function() {
		return Session.get('totalUpcomingEvents');
	},

	moreResults: function() {
		return !(Session.get('liveEventCount') < Session.get('liveDataLimit'));
	}
});

Template.sportsLive.onDestroyed(function() {
	$('#content').unbind('scroll');
});
