import active = Tracker.active;
interface Templates {
	sportsCategoryDetails: Template;
}

Template.sportsCategoryDetails.onCreated(function() {
	disableSite();
	Session.set('pageDataLimit', 16);
	this.setVar('showBrowseLink', false);
});

// Template.sportsCategoryDetails.onRendered(function() {
//
// 	$('#content').scroll(() => {
// 		var threshold, target = $('#showMoreResults');
// 		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('pageDataLimit', Session.get('pageDataLimit') + 16);
//
// 				let selector = {
// 					$and: [
// 						{
// 							$or: [
// 								{
// 									live: true,
// 									matchStatus: {$nin: Betting.liveFinishedStatuses},
// 									startTime: {$gt: moment(Betting.minute).add(3, 'hours').toDate()}
// 								},
// 								{
// 									live: false,
// 									startTime: {$gt: moment(Betting.minute).subtract(1, 'minute').toDate()},
// 									marketCount: {$gt: 0}
// 								}
// 							]
// 						},
// 						{
// 							$or: [
// 								{mainCategory: {$in: this.getVar('categories')}},
// 								{featCategory: {$in: this.getVar('categories')}}
// 							]
// 						}
// 					]
//
// 				};
// 				let options = {
// 					skip: Session.get('pageDataLimit') - 16,
// 					limit: Session.get('pageDataLimit'),
// 					sort: {startTime: 1}
// 				};
// 				let links = [
// 					{
// 						name: 'sport',
// 						options: {
// 							fields: {
// 								name: 1
// 							}
// 						}
// 					},
// 					{
// 						name: 'competition',
// 						options: {
// 							fields: {
// 								name: 1
// 							}
// 						}
// 					}
// 				];
// 				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', {_id: Session.get('opened-category')});
// 	});
//
// 	this.autorun(() => {
//
// 		if (!categorySub.ready()) {
// 			return;
// 		}
//
// 		let constructor = {
// 			$or: [
// 				{liveEventCount: {$gt: 0}},
// 				{eventCount: {$gt: 0}}
// 			]
// 		};
//
// 		let category = Betting.Category.db.findOne({_id: Session.get('opened-category')});
// 		if (!category) {
// 			console.log('No category found');
// 			return;
// 		}
//
// 		// Load everything relationally now that we have the necessary data from prev. sub
// 		let marketTypes = [category.root().mainPreLiveMarkets.ids[0], category.root().mainLiveMarkets.ids[0]];
// 		if (!marketTypes.length) {
// 			console.log('No market types');
// 			return;
// 		}
//
// 		Meteor.call('betting/categoryChildrenIds', Session.get('opened-category'), constructor, (err, data) => {
// 			this.setVar('categories', data);
// 			let selector = {
// 				$and: [
// 					{
// 						$or: [
// 							{
// 								live: true,
// 								matchStatus: {$nin: Betting.liveFinishedStatuses},
// 								startTime: {$gt: moment(Betting.minute).add(3, 'hours').toDate()}
// 							},
// 							{
// 								live: false,
// 								startTime: {$gt: moment(Betting.minute).subtract(1, 'minute').toDate()},
// 								marketCount: {$gt: 0}
// 							}
// 						]
// 					},
// 					{
// 						$or: [
// 							{mainCategory: {$in: this.getVar('categories')}},
// 							{featCategory: {$in: this.getVar('categories')}}
// 						]
// 					}
// 				]
// 			};
// 			let options = {
// 				skip: 0,
// 				limit: 16,
// 				sort: {startTime: 1}
// 			};
// 			let links = [
// 				{
// 					name: 'sport',
// 					options: {
// 						fields: {
// 							name: 1
// 						}
// 					}
// 				},
// 				{
// 					name: 'competition',
// 					options: {
// 						fields: {
// 							name: 1
// 						}
// 					}
// 				},
// 				{
// 					name: 'markets',
// 					selector: {
// 						type: {$in: marketTypes}
// 					}
// 				},
// 				{
// 					name: 'markets.selections'
// 				}
// 			];
// 			this.subscribe('betting/Event', selector, options, links, function() {
// 				enableSite();
// 			});
// 		});
// 	});
//
// 	Meteor.call('betting/rootChildrenCount', Session.get('opened-category'), (err, data) => {
// 		if (!data) {
// 			console.log('No root children!', data);
// 			return;
// 		}
// 		this.setVar('showBrowseLink', true);
// 	});
//
// 	Session.set('firstPageLoad', true);
//
// });

Template.sportsCategoryDetails.onRendered(function() {
	$('#content').scroll(() => {
		var threshold, target = $('#showMoreResults');
		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('pageDataLimit', Session.get('pageDataLimit') + 16);

				let selector = {
					$and: [
						{
							$or: [
								{
									live: true,
									matchStatus: {$nin: Betting.liveFinishedStatuses},
									startTime: {$gt: moment(Betting.minute).add(3, 'hours').toDate()}
								},
								{
									live: false,
									startTime: {$gt: moment(Betting.minute).subtract(1, 'minute').toDate()},
									marketCount: {$gt: 0}
								}
							]
						},
						{
							$or: [
								{mainCategory: {$in: this.getVar('categories')}},
								{featCategory: {$in: this.getVar('categories')}}
							]
						}
					]
				};

				let options = {
					skip: 0,
					limit: Session.get('pageDataLimit'),
					sort: {startTime: 1}
				};

				let links = [
					{
						name: 'sport',
					},
					{
						name: 'competition',
					},
					'mainCategoryPath',
					'featCategoryPath',
					'mainCategoryRoot',
					'featCategoryRoot',
					'mainCategory',
					'featCategory'
				];

				this.subscribe('betting/Event', selector, options, links, function() {
					enableSite();
				});

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

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

			}
		} else {
			if (target.data('visible')) {
				target.data('visible', false);
			}
		}
	});

	let constructor = {
		$or: [
			{liveEventCount: {$gt: 0}},
			{eventCount: {$gt: 0}}
		]
	};

	Meteor.call('betting/rootChildrenCount', Session.get('opened-category'), (err, data) => {
		if (!data) {
			return;
		}
		this.setVar('showBrowseLink', true);
	});

	Meteor.call('betting/categoryChildrenIds', Session.get('opened-category'), constructor, (err, data) => {
		if (!err) {
			this.setVar('categories', data);
		}
	});

	var categorySub;
	this.autorun(() => {
		categorySub = this.subscribe('betting/Category', {_id: Session.get('opened-category')});
	});

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

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

		let selector = {
			$and: [
				{
					$or: [
						{
							live: true,
							matchStatus: {$nin: Betting.liveFinishedStatuses},
							startTime: {$gt: moment(Betting.minute).add(3, 'hours').toDate()}
						},
						{
							live: false,
							startTime: {$gt: moment(Betting.minute).subtract(1, 'minute').toDate()},
							marketCount: {$gt: 0}
						}
					]
				},
				{
					$or: [
						{mainCategory: {$in: this.getVar('categories')}},
						{featCategory: {$in: this.getVar('categories')}}
					]
				}
			]
		};

		let options = {
			skip: 0,
			limit: 16,
			sort: {startTime: 1}
		};

		let links = [
			'mainCategoryPath',
			'featCategoryPath',
			'mainCategoryRoot',
			'featCategoryRoot',
			'mainCategory',
			'featCategory',
			'sport'
		];

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

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



	});

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

Template.sportsCategoryDetails.helpers({

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

	category: function() {
		var openedCategory = Session.get('opened-category');
		var cat = Betting.Category.db.findOne(openedCategory);
		if (!cat) {
			return;
		}
		return cat;
	},

	categories: function() {
		var activeCategoryId = Session.get('opened-category');
		if (!activeCategoryId) {
			return;
		}
		var activeCategory = Betting.Category.db.findOne(activeCategoryId);
		if (!activeCategory) {
			return;
		}
		var rootCategory = activeCategory.root();
		return Betting.Category.db.find({
			parent: rootCategory._id,
			$or: [
				{isFeatured: false},
				{isFeatured: {$exists: false}}
			]
		}, {sort: {orderNr: 1}});
	},

	openedCategory: function() {
		return Session.get('opened-category');
	},

	liveEvents: function() {
		var parent: Betting.Category = Betting.Category.db.selected().fetch()[0];
		if (!parent) {
			return;
		}
		var events = parent.openLiveEvents({sort: {startTime: 1, name: 1}});
		return _.unique(events);
	},

	root: function root(parentId = null) {
		var openedCategory = parentId ? parentId : Session.get('opened-category');
		var activeCategory = Betting.Category.db.findOne(openedCategory);
		if (!activeCategory) {
			return;
		}
		return activeCategory.root();
	},

	moreResults: function() {
		return !(Betting.Event.db.find().count() < Session.get('pageDataLimit'));
	},

	eventDays() {
		let events = Betting.Event.db.find({}, {sort: {startTime: 1}, limit: Session.get('pageDataLimit')}).fetch();
		let groupedEvents = _.groupBy(events, function(e) { return moment(e.startTime).format('YYYY.MM.D') });
		let groupedArr = [];

		for (let key in groupedEvents) {
			if (groupedEvents.hasOwnProperty(key)) {
				groupedArr.push({
					date: key,
					fixtures: groupedEvents[key]
				});
			}
		}
		return groupedArr;
	}

});

Template.sportsCategoryDetails.events({

	'click #tab-browse': function(e: MeteorTemplateEvent) {
		let category = Betting.Category.db.findOne({_id: Session.get('opened-category')});
		Pages.go('/sports/pre-live/' + category.makeSeoString() + '/browse/' + category._id);
	},

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

	'click button': function(e: MeteorTemplateEvent) {
		e.preventDefault();
		e.stopPropagation();
		Betting.toggleBet(this);
	}

});

Template.sportsCategoryDetails.onDestroyed(function() {
	$('#content').unbind('scroll');
});
