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

interface Templates {
	sportsSearchResults: Template;
}

Template.sportsSearchResults.onRendered(function(){
	this.autorun(() => {
		var term = Session.get('sportsSearchTerm');
		if (!term || term.length < 2) {
			return;
		}
		var cats = Betting.Category.db.find().fetch();
		var comps = [];
		cats.forEach(function (cat: Betting.Category) {
			comps = comps.concat(cat.competitions.ids);
		});
		comps = _.uniq(comps);
		var selector = {
			name: {$regex: term, $options: 'ig'},
			competition: {
				$in: Session.get('loadedCompetitions')
			},
			matchStatus: {$nin: [null, 'ended', 'interrupted', 'walkover', 'walkover1', 'walkover2',
				'retired', 'retired1', 'retired2', 'abandoned', 'after_ot'
				//'delayed', 'interrupted',
			]}
		};
		var options = {limit: 6, sort: {startTime: 1, name: 1}};
		this.subscribe('betting/Event', selector, options, ['competition']);
	});
});

Template.sportsSearchResults.helpers({

	results: function() {
		var term = Session.get('sportsSearchTerm');
		if (!term || term.length < 2) {
			return;
		}
		var selector = {
			name: {$regex: term, $options: 'ig'},
			competition: {
				$in: Session.get('loadedCompetitions')
			}
		};
		var options = {limit: 6, sort: {startTime: 1, name: 1}};

		return Betting.Event.db.find(selector, options).fetch().map((x) => {
			return {event: x}
		})
			.concat(<any>Betting.CategoryClient.db.find(selector, options).fetch().map((x) => {
				return {category: x}
			}));
	},

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

});

Template.sportsSearchResults.events({

	'click .odds, click .score, click h3, click .crumb': function(e: MeteorTemplateEvent) {
		e.stopPropagation();
		e.preventDefault();
		Session.set('showSearch', false);
		Pages.go(`/sports/${(this.live ? 'live' : 'pre-live')}/${this.makeSeoString()}/event/${this._id}`);
	},

	'click .search-category-res': function() {
		Session.set('showSearch', false);
		var live = Session.get('live') ? 'live' : 'pre-live';
		Pages.go(`/sports/${live}/${this.makeSeoString()}/events/${this._id}`);
	},

	'click .no-search-results': function() {
		Session.set('showSearch', false);
	}
});
