import React, { Component } from 'react'
import TrackerReact from 'meteor/ultimatejs:tracker-react';
import EventRow from './EventRow.jsx';

export default class CategoryDetails extends TrackerReact(Component) {

	constructor(props) {
		super(props);

		this.state = {
			limit: 16,
			subs: {
				categories: DDP.Subscription,
				events: []
			},
			categories: [],
			showBrowseLink: false
		};

		Tracker.autorun((catTracker) => {
			this.state.subs.categories = Meteor.subscribe('betting/Category', {_id: this.props.category});
			this.state.catTracker = catTracker;
		});

		Tracker.autorun((subTracker) => {
			if (!this.props.category) {
				return;
			}
			let constructor = {
				$or: [
					{liveEventCount: {$gt: 0}},
					{eventCount: {$gt: 0}}
				]
			};
			Meteor.call('betting/categoryChildrenIds', this.props.category, constructor, (err, data) => {
				this.state.categories = data;
				this.state.subs.events.push(this.doSubscribe(this.state.limit))
			});
			this.state.subTracker = subTracker;
		});

		Meteor.call('betting/rootChildrenCount', this.props.category, (err, data) => {
			if (!data) {
				return;
			}
			this.setState({ showBrowseLink: true });
		});

		this.onScroll = this.handleScroll.bind(this);
	}

	doSubscribe(limit) {

		let category = Betting.Category.db.findOne({_id: Session.get('opened-category')});
		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 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.state.categories}},
						{featCategory: {$in: this.state.categories}}
					]
				}
			]

		};
		let options = {
			skip: limit - 16,
			limit: limit,
			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'
			}
		];
		return Meteor.subscribe('betting/Event', selector, options, links);
	}

	events() {
		let events = Betting.Event.db.find({}, {sort: {startTime: 1}, limit: this.state.limit}).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,
					events: groupedEvents[key]
				});
			}
		}
		return groupedArr;
	}

	componentDidMount() {
		$('#content').scroll(this.onScroll);
	}

	handleScroll() {
		if (!this.state.subs.events.length || !this.state.subs.events[0].ready()) {
			return(<div>Loading events ... </div>)
		}
		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);
				this.setState({ limit: this.state.limit + 16 });
				this.doSubscribe(this.state.limit);
			}
		}
		else {
			if (target.data('visible')) {
				target.data('visible', false);
			}
		}
	}

	browseCategories() {
		let cat = Betting.Category.findOne({_id: this.props.category});
		Pages.go('/sports/pre-live/' + cat.makeSeoString() + '/browse/' + cat._id);
	}

	showEvents() {
		if (!this.state.subs.categories.ready()) {
			return(<div>Loading categories ... </div>)
		}
		if (!this.state.subs.events.length || !this.state.subs.events[0].ready()) {
			return(<div>Loading events ... </div>)
		}
		if (!this.events().length) {
			return(<div>we got nothing</div>)
		}
		return this.events().map((eventDay, i) => {
			return(
				<div key={i}>
					<h1 className="header">{eventDay.date}</h1>
					<div className="result-holder">
						{
							eventDay.events.map((event) => {
								return( <EventRow key={event._id} event={event} /> )
							})
						}
					</div>
				</div>
			)
		});
	}

	showBrowseLink() {
		let cat = Betting.Category.findOne({_id: this.props.category});
		if (!cat) {
			return;
		}
		if (this.state.showBrowseLink) {
			return(
				<li id="tab-browse" role="presentation" data-toggle="tab">
					<a href="#browse" onClick={ this.browseCategories.bind(this) } aria-controls="browse" role="tab" data-toggle="tab">Browse Category</a>
				</li>
			)
		}
	}

	componentWillUnmount() {
		this.state.catTracker.stop();
		this.state.subTracker.stop();
		this.state.subs.categories.stop();
		this.state.subs.events.forEach(function (sub) {
			sub.stop();
		});

		var subs = Meteor.default_connection._subscriptions; //all the subscriptions that have been subscribed.
		Object.keys(subs).forEach(function(key) {
			let sub = subs[key];
			if (sub.name == 'betting/Event') {
				sub.stop();
			}
		});

		window.removeEventListener('scroll', this.onScroll);
	}

	render() {

		return(
			<section className="sports sports-inner">
				<div className="container">
					<div className="submenu">
						<ul role="tablist" id="navTabs">
							<li id="tab-upcoming" role="presentation" className="active">
								<a href="#upcoming" aria-controls="upcoming" role="tab" data-toggle="tab">Live and upcoming</a>
							</li>
							{ this.showBrowseLink() }
						</ul>
					</div>
					<div className="tab-content">
						<div role="tabpanel" className="tab-pane fade in active" id="upcoming">
							<section className="content">
								{ this.showEvents() }
								<div id="showMoreResults" />
							</section>
						</div>
					</div>
				</div>
			</section>
		);
	}
}