interface Templates {
	sportsUpcoming: Template;
}

Template.sportsUpcoming.onCreated(function() {
	disableSite();
	Session.set('upcomingDataLimit', 10);
});

// Template.sportsUpcoming.onRendered(function(){
//
//	$('#content').scroll(() => {
		// var threshold, target = $('#showMoreUpcomingResults');
		// 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('upcomingDataLimit', Session.get('upcomingDataLimit') + 10);
		//
		// 		var options = {sort: {startTime: 1}};
		// 		var eventLimit = Session.get('upcomingDataLimit');
		// 		let selector = {
		// 			live: true,
		// 			matchStatus: 'not_started',
		// 			$or: [
		// 				{ mainCategory: { $in: Session.get('upcomingCategoryIds') } },
		// 				{ featCategory: { $in: Session.get('upcomingCategoryIds') } }
		// 			]
		// 		};
		// 		if (eventLimit) {
		// 			_.extend(options, {limit: eventLimit, skip: eventLimit - 10});
		// 		}
		// 		let links = [
		// 			{
		// 				name: 'markets'
		// 			},
		// 			{
		// 				name: 'competition'
		// 			},
		// 			{
		// 				name: 'markets.selections'
		// 			}
		// 		];
		// 		this.subscribe('betting/Event', selector, options, links);
		// 	}
		// } else {
		// 	if (target.data('visible')) {
		// 		target.data('visible', false);
		// 	}
		// }
// 	});
//
// 	var categorySub;
// 	this.autorun(() => {
// 		categorySub = this.subscribe('betting/Category', {liveEventCount: {$gt: 0}});
// 	});
//
// 	this.autorun(() => {
// 		if (!categorySub.ready()) {
// 			return;
// 		}
// 		let categories = Betting.Category.db.find().fetch();
// 		if (!categories) {
// 			return;
// 		}
// 		Session.set('upcomingCategoryIds', categories.map((c) => c._id));
// 	});
//
// 	this.autorun(() => {
//
// 		var options = {sort: {startTime: 1}};
// 		var eventLimit = 10;
// 		let selector = {
// 			live: true,
// 			matchStatus: 'not_started',
// 			$or: [
// 				{ mainCategory: { $in: Session.get('upcomingCategoryIds') } },
// 				{ featCategory: { $in: Session.get('upcomingCategoryIds') } }
// 			]
// 		};
// 		if (eventLimit) {
// 			_.extend(options, {limit: eventLimit, skip: eventLimit - 10});
// 		}
//
// 		let links = [
// 			{
// 				name: 'markets'
// 			},
// 			{
// 				name: 'competition'
// 			},
// 			{
// 				name: 'markets.selections'
// 			}
// 		];
//
// 		Meteor.call('betting/Event/total', selector, (err, data) => {
// 			Session.set('totalUpcomingEvents', data)
// 			this.subscribe('betting/Event', selector, options, links, function() {
// 				enableSite();
// 			});
// 		});
// 	});
//
// 	Session.set('firstLiveLoad', true);
// });

Template.sportsUpcoming.onRendered(function() {

	$('#content').scroll(() => {
		var threshold, target = $('#showMoreUpcomingResults');
		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('upcomingDataLimit', Session.get('upcomingDataLimit') + 10);
				let limit = Session.get('upcomingDataLimit');
				let eventSelector = {
					live: true,
					matchStatus: 'not_started',
					marketCount: {$gt: 0},
					startTime: {$gt: moment(Betting.minute).toDate()}
				};
				let eventOptions = {sort: {startTime: 1, name: 1}, limit: limit, skip: limit - 10};

				this.subscribe('betting/Event', eventSelector, eventOptions, ['mainCategoryPath', 'competition']);
				let events = Betting.Event.db.find(eventSelector, _.extend({fields: {mainCategoryPath: 1}}, eventOptions)).fetch();
				let eventIds = events.map(x => x._id);
				let marketTypes = _.uniq(events.reduce((all, cur) => all.concat(cur.listMarketTypeIds()), []));

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

	if (Session.get('upcomingDataLimit') == 10) {
		this.autorun(() => {
			var selector = {
				live: true,
				matchStatus: 'not_started',
				marketCount: {$gt: 0},
				startTime: {$gt: moment(Betting.minute).toDate()}
			};
			Meteor.call('betting/Event/total', selector, (err, data) => {
				if (!err) {
					Session.set('totalUpcomingEvents', data);
				}
			});
		});
	}


	this.autorun(() => {
		let eventSelector = {
			live: true,
			matchStatus: 'not_started',
			marketCount: {$gt: 0},
			startTime: {$gt: moment(Betting.minute).toDate()}
		};
		let eventOptions = {sort: {startTime: 1, name: 1}, limit: 10};

		this.subscribe('betting/Event', eventSelector, eventOptions, ['mainCategoryPath', 'competition']);

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

		let selector = {type: {$in: marketTypes}, event: {$in: eventIds}};
		this.subscribe('betting/Market', selector);
		this.subscribe('betting/Selection', selector);
		enableSite();
	});

	Session.set('firstLiveLoad', true);
});

Template.sportsUpcoming.helpers({

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

	events: function() {

		var options = {sort: {startTime: 1}};
		var eventLimit = Session.get('upcomingDataLimit');
		if (eventLimit) {
			_.extend(options, {limit: eventLimit});
		}

		var selector = {live: true};

		return Betting.Event.db.find(selector, options);
	},

	moreResults: function() {
		return !(Session.get('totalUpcomingEvents') < Session.get('upcomingDataLimit'));
	},

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

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

	iconClass: function(sportName) {
		if (!sportName) {
			return;
		}
		return sportName.replace(/\s+/g, '-').toLowerCase();
	}

});

Template.sportsUpcoming.events({

	'click .upcoming-event': function(e: MeteorTemplateEvent) {
		e.preventDefault();
		Pages.go(`/sports/pre-live/${this.makeSeoString()}/event/${this._id}`);
	}

});

Template.sportsUpcoming.destroyed = function() {

	$('#content').unbind('scroll');
}

function loadMore(self) {
	var threshold, target = $('#showMoreUpcomingResults');
	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('upcomingDataLimit', Session.get('upcomingDataLimit') + 10);
			let limit = Session.get('upcomingDataLimit');
			let eventSelector = {
				live: true,
				matchStatus: 'not_started',
				marketCount: {$gt: 0},
				startTime: {$gt: moment(Betting.minute).toDate()}
			};
			let eventOptions = {sort: {startTime: 1, name: 1}, limit: limit, skip: limit - 10};

			let sub = this.subscribe('betting/Event', eventSelector, eventOptions, ['mainCategoryPath', 'competition']);
			if (!sub.ready()) {
				return;
			}
			let events = Betting.Event.db.find(eventSelector, _.extend({fields: {mainCategoryPath: 1}}, eventOptions)).fetch();
			let eventIds = events.map(x => x._id);
			let marketTypes = _.uniq(events.reduce((all, cur) => all.concat(cur.listMarketTypeIds()), []));

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

}

function doSubscribe(self) {
	let limit = Session.get('upcomingDataLimit');
	let eventSelector = {
		live: true,
		matchStatus: 'not_started',
		marketCount: {$gt: 0},
		startTime: {$gt: moment(Betting.minute).toDate()}
	};
	let eventOptions = {sort: {startTime: 1, name: 1}, limit: limit, skip: limit - 10};

	let sub = self.subscribe('betting/Event', eventSelector, eventOptions, ['mainCategoryPath', 'competition']);
	if (!sub.ready()) {
		return;
	}
	let events = Betting.Event.db.find(eventSelector, _.extend({fields: {mainCategoryPath: 1}}, eventOptions)).fetch();
	let eventIds = events.map(x => x._id);
	let marketTypes = _.uniq(events.reduce((all, cur) => all.concat(cur.listMarketTypeIds()), []));

	let selector = {type: {$in: marketTypes}, event: {$in: eventIds}};
	self.subscribe('betting/Market', selector);
	self.subscribe('betting/Selection', selector);
}