import Head from 'next/head'
import Countdown from 'react-countdown';
import { Footer } from '../components/Footer/Footer'
import { Navbar } from '../components/Navbar/Navbar'
import { Compteur } from '../components/Score/Compteur'
import styles from '../styles/Home.module.css'
import { w3cwebsocket as W3CWebSocket } from "websocket";
import { useEffect, useState } from 'react';

export default (props) => {
  let context = {};
  let time = null;
  let scoreA = 0;
  let scoreB = 0;
  let isTeam = false;
  let [restTime, setTime] = useState(0);
  let websocket = new W3CWebSocket('ws://localhost:1235')
  const team = ["Rouge", "Bleu", "Vert", "Jaune", "Cyan", "Rouge", "Bleu", "Vert", "Jaune", "Cyan"];
  const score = [0,0,0,0,0,0,0,0,0,0]

  useEffect(() => {
    console.log("test");
    const url = "http://localhost:1235/party/start";
    fetch(url)
      .then(response => response.json())
      .then(json => {
        context = json;
        setRestTime()
        if (json.players && json.players.length > 0 && json.players[0].team) {
          isTeam = true;
        }
        console.log(context);
      })
    initWs();
  })

  const setRestTime = () => {
    if (context.winCondition && context.winCondition.time && context.start) {
      const now = Date.now();
      time = context.winCondition.time;
      const start = context.start;
      const res = time - (now - start);
      setTime(res > 0 ? res : 0)
    }
  }

  const initWs = () => {
    websocket.onmessage = message => {
      const json = JSON.parse(message);
      const ctx = json.context;
      context = ctx;
    };
  }

  const renderTimer = ({ hours, minutes, seconds, completed }) => {
    if (completed) {
      const requestOptions = {
        method: 'GET',
        redirect: 'follow'
      };

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

    return <span>{hours}:{minutes}:{seconds}</span>
  }

  return (
    <div>
      <Head>
        <title>Palu-IoT - Laser Game {time}</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Navbar />
      <main className={styles.main}>
        <div className="container bg-dark p-5 text-white bg-opacity-25 border border-5 border-white">
          <div className="row">
            <div className="col-sm py-2 d-flex align-items-center justify-content-center">
              <Countdown
                date={restTime + Date.now()}
                renderer={renderTimer}
              />
            </div>
          </div>
          <div class="row">
            {team.map((x, i) =>
              <div className="col-md py-2 d-flex align-items-center justify-content-center">
                <Compteur score={score[i]} teamName={x} />
              </div>
            )}
          </div>
        </div>
      </main>
      <Footer />
    </div>
  )
}