import { Component } from "react";
import Router from 'next/router';

export class Player extends Component {

    constructor(props) {
        super(props);
        this.state = {
            playersName: [],
            playersId: [],
            playerCount: 0,
            name: "",
            isTeam: true,
            team: null
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }

    componentDidMount() {
        const url = "http://localhost:1235/party/current";
        fetch(url)
            .then(response => response.json())
            .then(json => {
                console.log(json);
                this.setState({
                    playersName: json.players.map(p => p.name),
                    playersId: json.players.map(p => p.key),
                    isTeam: json.players.map(p => (p.isTeam === false ? false : true))
                })
            })
    }

    handleChange(event) {
        if (event.target.name === "name") {
            this.setState({
                name: event.target.value
            });
        } else if (event.target.name === "team") {
            this.setState({
                team: event.target.value
            });
        }
    }

    handleSubmit(event) {
        const myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");

        console.log("alo");
        console.log(this.state.team);
        const raw = JSON.stringify({
            name: this.state.name,
            team: this.state.team
        });

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: raw,
            redirect: 'follow'
        };

        fetch("http://localhost:1235/party/update/" + this.state.playersId[this.state.playerCount], requestOptions)
            .then(response => response.text())
            .then(result => console.log(result))
            .catch(error => console.log('error', error));

        this.isAllPlayerReady(event);
    }

    handleClick(event) {
        //send remove player
        this.isAllPlayerReady(event)
    }

    isAllPlayerReady(event) {
        this.setState({ name: "" })
        this.setState({ playerCount: this.state.playerCount + 1 }, function () {
            console.log(this.state.playerCount);
            console.log(this.state.playersName.length);
            if (this.state.playersName.length > this.state.playerCount) {
                var requestOptions = {
                    method: 'GET',
                    redirect: 'follow'
                };

                fetch("http://localhost:1235/party/ping/" + this.state.playersId[this.state.playerCount], requestOptions)
                    .then(response => response.text())
                    .then(result => console.log(result))
                    .catch(error => console.log('error', error));
            } else {
                const requestOptions = {
                    method: 'GET',
                    redirect: 'follow'
                };

                fetch("http://localhost:1235/party/start", requestOptions)
                    .then(response => response.text())
                    .then(result => console.log(result))
                    .catch(error => console.log('error', error));
                Router.push('/game')
            }

            event.preventDefault();
            event.stopPropagation();
        });
    }



    render() {
        return (
            <div className="p-5 my-5 bg-light border-bottom text-center">
                <h1 className="display-5 fw-bold">{this.state.playersName[this.state.playerCount]}</h1>
                <div className="col-lg-6 mx-auto">
                    <form className="row g-3" onSubmit={this.handleSubmit}>
                        <div className="form-floating mb-3">
                            <input name="name" type="text" className="form-control" id="name" placeholder="Username" value={this.state.name} onChange={this.handleChange} required />
                            <label for="name">Pseudo</label>
                        </div>
                        <div className="mb-3">
                            
                            <select name="team" class="form-select" aria-label="Default select example" onChange={this.handleChange} disabled={!this.state.isTeam} required>
                                <option value="" selected>Choix de l'equipe</option>
                                <option value="A">A</option>
                                <option value="B">B</option>
                            </select>
                        </div>
                        <div className="d-grid gap-2 d-sm-flex justify-content-sm-center">
                            <button type="submit" className="btn btn-primary btn-lg px-4 gap-3">Valider</button>
                            <button type="button" className="btn btn-outline-secondary btn-lg px-4" onClick={this.handleClick}>Ne participe pas</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}