import * as React from "react";

import Typography from "@material-ui/core/Typography";
import Paper from "@material-ui/core/Paper";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import LinearProgress from "@material-ui/core/LinearProgress";
import Snackbar from "@material-ui/core/Snackbar";

import { withRouter } from "react-router-dom";

import { BACKEND_URL } from "../config";

interface IProps {
    history: any;

    setLoading: (state: boolean) => void;
    setSnackbar: (state: boolean, msg: string) => void;

    loading: boolean;
    snackOpen: boolean;
    snackMsg: string;
}

const RegisterPageWithRouter = withRouter(
    class RegisterPage extends React.Component<IProps> {
        private usernameRef: HTMLInputElement = {} as HTMLInputElement;
        private passwordRef: HTMLInputElement = {} as HTMLInputElement;
        private passwordRepRef: HTMLInputElement = {} as HTMLInputElement;
        private classRef: HTMLInputElement = {} as HTMLInputElement;

        setSnackbar = (state: boolean, msg: string) => {
            this.props.setSnackbar(state, msg);
        }

        performRegister = () => {
            // Check the passwords
            const password = this.passwordRef.value;
            const repeat = this.passwordRepRef.value;
            const username = this.usernameRef.value;
            const classId = this.classRef.value;

            if (!password || !repeat || !username || !classId) {
                this.setSnackbar(true, "Nicht alle Felder sind ausgefüllt");
                return;
            }

            if (password.length < 6) {
                this.setSnackbar(true, "Das Passwort ist zu kurz (< 6)");
                return;
            }

            if (password !== repeat) {
                this.setSnackbar(true, "Die Passwörter stimmen nicht überein");
                return;
            }

            this.props.setLoading(true);
            fetch(`${BACKEND_URL}/api/register`, {
                headers: new Headers({
                    "Content-Type": "application/json",
                }),
                method: "POST",
                body: JSON.stringify({
                    username,
                    password,
                    classId,
                }),
            }).then(resp => resp.json(), err => {
                console.log("RegisterPage::performRegister: Error trying to decode data");
                this.props.setLoading(false);
            }).then(data => {
                this.props.setLoading(false);

                // Check the error code
                if (data.error === "200") {
                    this.props.history.push("/login");
                } else {
                    this.setSnackbar(true, "Ein Fehler ist aufgetreten");
                    console.log(data);
                }
            });
        }

        render() {
            // Trigger a login when return is pressed
            const onEnter = (event: any) => {
                if (event.key === "Enter") {
                    this.performRegister();
                }
            };

            return <div>
                <Grid
                    container
                    spacing={0}
                    direction="column"
                    alignItems="center"
                    justify="center"
                    style={{ minHeight: '100vh' }}>
                    <Grid item xs={12}>
                        <Paper className="paper">
                            <Typography variant="title">Registrierung</Typography>
                            <Grid container direction="column" spacing={8}>
                                <Grid item>
                                    <TextField
                                        label="Username"
                                        onKeyPress={onEnter}
                                        inputRef={node => this.usernameRef = node} />
                                </Grid>
                                <Grid item>
                                    <TextField
                                        label="Passwort"
                                        type="password"
                                        onKeyPress={onEnter}
                                        inputRef={node => this.passwordRef = node} />
                                </Grid>
                                <Grid item>
                                    <TextField
                                        label="Passwort wiederholen"
                                        type="password"
                                        onKeyPress={onEnter}
                                        inputRef={node => this.passwordRepRef = node} />
                                </Grid>
                                <Grid item>
                                    <TextField
                                        label="Klassencode"
                                        onKeyPress={onEnter}
                                        inputRef={node => this.classRef = node} />
                                </Grid>

                                <Grid item>
                                    {
                                        this.props.loading ? (
                                            <LinearProgress />
                                        ) : undefined
                                    }
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        className="login-btn"
                                        onClick={() => this.performRegister()}>
                                        Registrieren
                                </Button>
                                </Grid>
                            </Grid>
                        </Paper>
                    </Grid>
                </Grid>
                <Snackbar
                    open={this.props.snackOpen}
                    onClose={() => this.props.setSnackbar(false, "")}
                    message={this.props.snackMsg}
                    autoHideDuration={6000} />
            </div>;
        }
    }
);
export default RegisterPageWithRouter;
