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

interface Templates {
	default: Template;
	userbox: Template;
	landinglayout: Template;
}

Template.default.onRendered(function() {
	restrictUK();

	this.autorun(() => {
		// if (!sub.ready()) {
		// 	return;
		// }

		var categories = Betting.Category.db.find();
		var competitions = [];
		var sports = [];

		categories.forEach(function (category) {
			competitions.push(category.competitions.ids);
			sports.push(category.sport.id);
		});

		competitions = _.uniq(_.flatten(competitions));
		this.subscribe('betting/Competition', {
			_id: {$in: competitions},
			$or: [
				{eventCount: {$gt: 0}},
				{liveEventCount: {$gt: 0}}
			]
		});

		Session.set('loadedCompetitions', competitions);

		var betSlip = Betting.getBetSlip();

		if (betSlip && betSlip.length) {
			this.subscribe('betting/Selection', {_id: {$in: betSlip.map((x) => x.selection)}});
			this.subscribe('betting/Market', {_id: {$in: betSlip.map((x) => x.marketId)}});
			this.subscribe('betting/Event', {_id: {$in: betSlip.map((x) => x.eventId)}});
		}

		var openedCatId = Session.get('opened-category');
		if (!openedCatId) {
			Betting.Category.db.clearSelection();
			return;
		}
		var category = Betting.Category.db.findOne(openedCatId);
		if (!category) {
			return;
		}
		category.selectOne();
	});

});

Template.default.helpers({

	betslipOpen: function() {
		return Session.get('betslip-open');
	},

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

});

Template.default.events({

	'click .effect-moveleft.active, click .close, click .nav-logo': function(e: MeteorTemplateEvent) {
		e.stopPropagation();
		Session.set('menuExpanded', false);

		var activePage = typeof Pages.active().title == 'function' ? (<any>Pages.active()).title() : Pages.active().title;

		googleSend({
			'eventCategory': 'Header',
			'eventAction': 'Closed the side menu',
			'pageActiveTab': activePage,
			'pageEventArea': 'Header'
		});

	},

	'click .logout': function() {
		Pages.go('/');
		Meteor.logout();
		Session.set('menuExpanded', false);
	}

});

Template.userbox.helpers({

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

	balance: function () {
		return Math.floor(Rewards.userTotalBalance(Users.Profile.active()) * 100000) / 100;
	}

});

Template.userbox.events({

	'click ul a': function(e: MeteorTemplateEvent) {
		var activePage = typeof Pages.active().title == 'function' ? (<any>Pages.active()).title() : Pages.active().title;
		googleSend({
			'eventCategory': 'Header',
			'eventAction': 'Clicked Element in Side Nav',
			'eventLabel': $(e.currentTarget).text(),
			'pageActiveTab': activePage,
			'pageEventArea': 'Sidebar'
		});

	}

});

function restrictUK() {
	Countries.IpClient.getConnectionCountry(function (err, res) {
		if (err) return;
		Session.set('clientCountry', res.code);
		if (res.code == 'GB' || res.code == 'AU') {
			Modals.open('gbError');
		}
	});
}
