interface Templates {
	sportsHome: Template;
}

Template.sportsHome.onCreated(function () {

	disableSite();

	if (!this.getVar('homeEventCount')) {
		this.setVar('homeEventCount', 2);
	}

	if (!this.getVar('homeFeaturedCount')) {
		this.setVar('homeFeaturedCount', 3);
	}

});

Template.sportsHome.onRendered(function() {

	// Load the featured category and any competitions assosiated with it
	let featCatConstructor = {
		isFeatured: true,
		level: 0,
		$or: [
			{eventCount: {$gt: 0}},
			{liveEventCount: {$gt: 0}}
		]
	};
	let featCatOptions = {
		fields: {
			name: 1,
			orderNr: 1,
			isFeatured: 1,
			competitions: 1,
			level: 1,
			listLiveMarkets: 1,
			listPreLiveMarkets: 1,
			eventCount: 1,
			liveEventCount: 1,
			sport: 1,
		}, sort: {orderNr: 1}
	};

	this.autorun(() => {
		this.subscribe('betting/Category', featCatConstructor, featCatOptions, ['sport']);
	});

	this.autorun(() => {

		let category = Betting.Category.db.findOne(featCatConstructor, featCatOptions);
		if (!category) {
			return;
		}

		// Load everything relationally now that we have the necessary data from prev. sub
		let marketTypes = [category.root().listPreLiveMarkets.ids[0], category.root().listLiveMarkets.ids[0]];
		if (!marketTypes.length) {
			return;
		}

		let featEventsLinks = [

			{"name": 'sport'},
			{
				name: 'competitions',
				options: {
					fields: {
						events: 1,
						name: 1
					}
				}
			},
			{
				name: 'competitions.events',
				selector: {
					$or: [
						{live: true, matchStatus: {$nin: Betting.liveFinishedStatuses}},
						{
							live: false,
							startTime: {$gt: moment(Betting.minute).subtract(1, 'minute').toDate()},
							marketCount: {$gt: 0}
						}
					]
				},
				options: {
					fields: {
						name: 1,
						startTime: 1,
						sport: 1,
						competition: 1,
						outright: 1,
						live: 1,
						active: 1,
						liveMarketCount: 1,
						marketCount: 1,
						markets: 1,
						matchStatus: 1,
						mainCategoryPath: 1
					},
					limit: 10,
					sort: {
						startTime: 1
					}
				}
			},
			{
				name: 'competitions.events.sport'
			},
			{
				name: 'competitions.events.mainCategoryPath'
			},
			{
				name: 'competitions.events.featCategoryPath'
			},
			{
				name: 'competitions.events.mainCategoryRoot'
			},
			{
				name: 'competitions.events.featCategoryRoot'
			},
			{
				name: 'competitions.events.mainCategory'
			},
			{
				name: 'competitions.events.featCategory'
			},
			{
				name: 'competitions.events.markets',
				selector: {
					type: {$in: marketTypes}
				}
			},
			{
				name: 'competitions.events.markets.selections'
			}
		];
		this.subscribe('betting/Category', {_id: category._id}, featCatOptions, featEventsLinks);

		// Load "all sports"
		let allSportsConstructor = {
			level: 0,
			isFeatured: false,
			$or: [
				{eventCount: {$gt: 0}},
				{liveEventCount: {$gt: 0}}
			]
		};
		this.subscribe('betting/Category', allSportsConstructor, {}, {fields: {name: 1}}, function() {
			enableSite();
		});
	});

	this.autorun(() => {
		let bannerSelector = {
			mobile: true,
			startDate: {$lte: new Date()},
			endDate: {$gt: new Date()}
		};
		this.subscribe('betting-banner/banners', bannerSelector);
	});

});

Template.sportsHome.helpers({

	'loading': function () {
		var tpl = Template.instance();
		if (!tpl.subscriptionsReady()) {
			return true;
		}
		return false;
	},

	'category': function () {
		var tpl = Template.instance();
		if (!tpl.subscriptionsReady()) {
			return;
		}
		var homeCategory = Betting.Category.db.findOne({isFeatured: true, level: 0}, {sort: {orderNr: 1}});
		return Betting.Category.db.findOne({_id: homeCategory});
	},

	'events': function () {
		var tpl = Template.instance();
		if (!tpl.subscriptionsReady()) {
			return;
		}

		var category = Betting.Category.db.findOne({isFeatured: true, level: 0}, {sort: {orderNr: 1}});
		if (!category) {
			return;
		}

		var options = {sort: {startTime: 1}};
		if (tpl.getVar('homeEventCount')) {
			_.extend(options, {limit: tpl.getVar('homeEventCount')});
		}

		var events = _.unique(category.allEvents({}, options));
		return _.sortBy(events, function(e) {return moment(e.startTime); });

	},

	featuredCategories: function () {
		var tpl = Template.instance();
		if (!tpl.subscriptionsReady()) {
			return;
		}
		var selector = <any>{level: 0, isFeatured: true, $or: [{eventCount: {$gt: 0}}, {liveEventCount: {$gt: 0}}]};
		var options = {sort: {orderNr: 1}};
		if (tpl.getVar('homeFeaturedCount')) {
			_.extend(options, {limit: tpl.getVar('homeFeaturedCount')});
		}

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

	featuredCategoriesCount: function () {
		var selector = <any>{level: 0, isFeatured: true, $or: [{eventCount: {$gt: 0}}, {liveEventCount: {$gt: 0}}]};
		return Betting.Category.db.find(selector).count();
	},

	sports: function () {
		var tpl = Template.instance();
		if (!tpl.subscriptionsReady()) {
			return;
		}
		var selector = <any>{
			level: 0,
			isFeatured: false,
			$or: [
				{eventCount: {$gt: 0}},
				{liveEventCount: {$gt: 0}}
			]
		};
		var options = {sort: {orderNr: 1}};

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

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

	banner: function() {
		let a = Betting.Banner.db.findOne();
		if (!a) {
			return;
		}
		return a;
	}

});

Template.sportsHome.events({

	'click .all-home-events': function () {
		var tpl = Template.instance();
		tpl.setVar('homeEventCount', tpl.getVar('homeEventCount') ? false : 2);
	},

	'click .all-featured-categories': function () {
		var tpl = Template.instance();
		tpl.setVar('homeFeaturedCount', tpl.getVar('homeFeaturedCount') ? false : 3);
	},

	'click .content .menu a:not(.virtual-sports)': function () {
		Pages.go(`/sports/pre-live/${this.makeSeoString()}/events/${this._id}`);
	},

	'click .virtual-sports': function() {
		document.location.href = '/casino/virtual-sports/kiron-virtual-sports';
	}
});
