import * as React from "react";

import Table from "@material-ui/core/Table";
import TableHead from "@material-ui/core/TableHead";
import TableBody from "@material-ui/core/TableBody";
import TableRow from "@material-ui/core/TableRow";
import TableCell from "@material-ui/core/TableCell";
import Typography from "@material-ui/core/Typography";

import { TopTen } from "../models/learner";
import { userScoreToLevel } from "../models/user";

interface IProps {
    topTen: TopTen[];
}

export default class Scoreboard extends React.Component<IProps> {
    private unique = 0;

    constructor(props: any) {
        super(props);

        this.genId = this.genId.bind(this);
        this.tableRow = this.tableRow.bind(this);
    }

    genId() {
        return "SCOREBOARD" + this.unique++;
    }

    tableRow(learner: TopTen) {
        // Gotta show respect! (That Unicode monster is a crown)
        const username = {
            false: learner.username,
            true: `${learner.username} 👑`
        }[learner.nr === 1];

        return <TableRow key={this.genId()}>
            <TableCell>
                <Typography variant="title" component="b">
                    {learner.nr}
                </Typography>
            </TableCell>
            <TableCell>
                <Typography component="b">{username}</Typography>
            </TableCell>
            <TableCell numeric>
                {userScoreToLevel(learner.score).level}
            </TableCell>
            {/* To make this fit on both mobile and desktop, we don't use
                numeric, as it would otherwise look weir otherwise look weird */}
            <TableCell numeric>{learner.score}</TableCell>
        </TableRow>
    }

    render() {
        const sortedLearners = this.props.topTen.sort((a, b) => {
            if (a.score > b.score) {
                return -1;
            } else if (a.score < b.score) {
                return 1;
            }

            return 0;
        });

        return <Table padding="none">
            <TableHead>
                <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell>User</TableCell>
                    <TableCell numeric>Level</TableCell>
                    <TableCell numeric>Punktzahl</TableCell>
                </TableRow>
            </TableHead>
            <TableBody>
                {sortedLearners.map(this.tableRow)}
            </TableBody>
        </Table>;
    }
}
