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

interface Templates {
	sportsEventDetails: Template;
}


Template.sportsEventDetails.onCreated(function() {
	disableSite();
	Session.set('marketsExtended', false);
	Session.set('widgetLoaded', false);
});

Template.sportsEventDetails.onRendered(function() {

	this.autorun(() => {

		let widgetSupportedSports = ['1','2','4','5','6','12','23','31'];
		var marketSelector = {event: Session.get('opened-event')};
		this.subscribe('betting/Event', {_id: Session.get('opened-event')}, {}, ['competition', 'mainCategory', 'featCategory', 'mainCategoryRoot', 'featCategoryRoot', 'sport']);

		let event: Betting.Event = Betting.Event.db.findOne(Session.get('opened-event'));
		if (!event) {
			return;
		}

		if (event.sport && event.sport.fetch()) {
			if (widgetSupportedSports.indexOf(event.sport.fetch()._id) !== -1) {

				var widgetHandle = SRLive.addWidget({
					name: "widgets.lmts",
					config: {
						"height": false,
						"showScoreboard": true,
						"showMomentum": true,
						"showMomentum2": true,
						"momentum2_type": "line",
						"momentum2_showArea": true,
						"showPitch": true,
						"showSidebar": true,
						"showGoalscorers": true,
						"sidebarLayout": "dynamic",
						"collapse_enabled": true,
						"collapse_startCollapsed": true,
						"matchId": event._id,
						"showTitle": false,
						"container": ".wc-widget"
					},
					callback: function () {
						Session.set('widgetLoaded', true);
					}
				});
				Session.set('widgetHandle', widgetHandle);
			}
		}

		let rootCategory = event.rootCategory();
		if (rootCategory) {
			let marketTypes = rootCategory.mainPreLiveMarkets.ids.concat(rootCategory.mainLiveMarkets.ids);

			if (!Session.get('marketsExtended') && marketTypes.length) {
				_.extend(marketSelector, {type: {$in: marketTypes}});
			}
		}

		this.subscribe('betting/Market', marketSelector, () => {

			let markets = Betting.Market.db.find().count();
			if (!markets) {
				this.subscribe('betting/Market', {event: Session.get('opened-event')});
			}

		});
		this.subscribe('betting/Selection', {event: Session.get('opened-event')}, function() {
			enableSite();
		});
		let isLive = event.live && event.active ? 'Live In-Play' : '';
		setMeta('title', `Bitcoin ${normaliseStr(event.name)} ${isLive} Betting Odds at Sportsbet.io`);
		setMeta('description', `${normaliseStr(event.name)} ${isLive} Bitcoin Betting from Sportsbet.io, All the ${event.category().name} Betting Odds Available on Desktop & Mobile!`);

		Meteor.setTimeout(function() {
			if ($('.sr-content').html() == '' || $('.sr-no-data-message').html() == 'Not available') {
				Session.set('widgetLoaded', false);
			}
		}, 650);

	});
});

Template.sportsEventDetails.helpers({

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

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

	event: function() {
		return Betting.Event.db.findOne({
			_id: Session.get('opened-event'),
			$or: [{live: true}, {live: false, startTime: {$gt: moment(Betting.minute).add(1, 'minute').toDate()}}]
		});
	},

	groupedMarkets: function() {
		var event = Betting.Event.db.findOne({_id: Session.get('opened-event')});
		if (!event) {
			return;
		}

		if (event.live && event.matchStatus === 'ended') {
			return;
		}

		var groupedMarkets = [];
		var markets: Betting.Market[] = event.visibleMarkets();
		if (!markets) {
			return;
		}

		markets.forEach(function(m) {
			var templateHandle = (m.live ? 'live' : 'prelive') + '_' + (+m.details.subType || m.details.typeId);
			var obj = <any>{
				name: m.name,
				market: m,
				template: Betting.getMarketTpl(templateHandle),
				handle: templateHandle
			};
			groupedMarkets.push(obj);
		});

		return _
			.chain(groupedMarkets)
			.groupBy('name')
			.map(function(value, key) {
				return {
					name: key,
					template: value[0].template,
					handle: value[0].handle,
					markets: _.pluck(value, 'market')
				}
			})
			.value();
	},

	selections: function () {
		var self = <Betting.Market>this;
		if (self.name === '') {
			return self.orderedByOddsSelections();
		}
		else {
			return self.orderedSelections();
		}
	},

	selectionCount: function() {
		var self: Betting.Market = (<Betting.Selection>this).market.fetch();
		if (!self) {
			return;
		}
		var total = self.activeSelections().count();
		if (total % 3 === 0) {
			return 4;
		}
		if (total % 2 === 0) {
			return 6;
		}
		if (total % 2 === 1) {
			return 4;
		}
		if (total % 5 === 0) {
			return 12;
		}
		if (total % 5 === 1) {
			return 12;
		}
	},

	playedMinutes: function () {
		if (!(<any>this).sport || !(<any>this).results || !(<any>this).results.matchMinute) {
			return;
		}
		return (<any>this).results.matchMinute + `'`;
	},

	scores: function() {
		var event = Betting.Event.db.findOne({
			_id: Session.get('opened-event'),
			$or: [{live: true}, {live: false, startTime: {$gt: moment(Betting.minute).add(1, 'minute').toDate()}}]
		});
		return event.getScore(true);
	},

	sportClass: function() {
		var event = Betting.Event.db.findOne({
			_id: Session.get('opened-event'),
			$or: [{live: true}, {live: false, startTime: {$gt: moment(Betting.minute).add(1, 'minute').toDate()}}]
		});
		var sport = event.sport.fetch();
		if (!sport._id) {
			return;
		}
		return sport.name.toLowerCase().replace(/\s/g, '-');
	},

	marketsExtended() {
		return Session.get('marketsExtended');
	}

});

Template.sportsEventDetails.events({

	'click section header': function(e: MeteorTemplateEvent) {
		var section = $(e.currentTarget).parent();
		section.hasClass('expanded') ? section.removeClass('expanded') : section.addClass('expanded');
	},

	'click .additional a': function(e: MeteorTemplateEvent) {
		e.preventDefault();
		e.stopPropagation();
		if (this.suspended()) {
			return;
		}
		Betting.toggleBet(this);
	},

	'click .all-markets-button': function() {
		Session.set('marketsExtended', true);
	}

});

Template.sportsEventDetails.onDestroyed(function() {
	if (Session.get('widgetHandle')) {
		SRLive.removeWidget(Session.get('widgetHandle'));
	}
});

function containsObject(obj, list) {
	var res = _.find(list, function(val){ return _.isEqual(obj, val)});
	return (_.isObject(res))? true:false;
}
