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

export default class LeaderboardUsers extends TrackerReact(Component) {

	constructor() {
		super();
		this.state = {
			limit: 20
		}
	}

	users() {

		let prizesColl = Betting.LeaderboardPrize.db.find({leaderboard: this.props.leaderboard._id}).fetch();
		let prizesArr = [];

		prizesColl.forEach(function (p) {
			prizesArr[p.position] = p.prize;
		});

		return this.props.leaderboard.users.fetch({}, {sort: {points: -1}, limit: this.state.limit}).map((user, i) => {
			let profile = user.user.fetch();
			let str = profile.username.substr(0, 4);
			let scrambled = profile.username.substr(4);
			let asterixes = new Array(scrambled.length + 1).join('*');
			return {
				position: (i + 1),
				username: str + asterixes,
				email: profile.email,
				points: user.points.toFixed(2),
				prize: prizesArr[(i + 1)]
			}
		});
	}

	showPrize(user) {
		if (!user.prize) {
			return;
		}
		return(
			<div>{user.prize * 1000} <small className="text-muted">mBTC</small></div>
		);
	}

	toggleList() {
		this.setState({ limit: this.state.limit == 20 ? 2000 : 20 });
	}

	render() {
		return (
			<div>
				<h2>Current Rankings</h2>
				<hr />
				<table className="table table-striped">
					<thead>
						<tr>
							<th>#</th>
							<th>Username</th>
							<th>Points</th>
							<th>Prize</th>
						</tr>
					</thead>
					<tbody>
						{
							this.users().map((user, i) => {
								return(
									<tr key={i}>
										<td><b>{user.position}</b></td>
										<td>{user.username}</td>
										<td>{user.points}</td>
										<td>{this.showPrize(user)}</td>
									</tr>
								)
							})
						}
					</tbody>
				</table>
				<button onClick={this.toggleList.bind(this)} className="full-list-button">{ this.state.limit == 20 ? 'Show more' : 'Show Top 20' }</button>
			</div>
		)
	}
}