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 isTeam = false;
  let [restTime, setTime] = useState(10000);
  let websocket = new W3CWebSocket('ws://localhost:1235')
  let team = ["A", "B"]
  let [score, setScore] = useState([1, 3]);



  useEffect(() => {
    console.log("useEffect");
    const url = "http://localhost:1235/party/start";
    async function fetchContext() {
      const response = await fetch(url)
      const json = await response.json();
      context = json;
      setRestTime()
      if (json.players && json.players.length > 0 && json.players[0].team) {
        isTeam = true;
      }
      initTeam();
      updateTeamPoint();
    }
    fetchContext()
    websocket.onmessage = message => {
      console.log("ws");
    };
  }, score)

  const initTeam = () => {
    let array = [];
    if (context.isTeam) {
      for (let p in context.isTeam) {
        array.push(p)
      }
    } else {
      for (let p of context.players) {
        array.push(p.name)
      }
    }
    team = array;
  }

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

  const updateTeamPoint = () => {
    let array = [];
    if (context.isTeam) {
      for (const [key, value] of Object.entries(context.isTeam)) {
        array.push(value)
      }
    } else {
      for (let p of context.players) {
        array.push(p.count)
      }
    }
    setScore(array)
  }

  const renderTimer = ({ hours, minutes, seconds, completed, api }) => {
    if (completed) {
      const requestOptions = {
        method: 'GET',
        redirect: 'follow'
      };
      console.log("renderTimer");
      fetch("http://localhost:1235/party/finish", requestOptions)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));
    }
    return <h1> {hours<10?"0":""}{hours} : {minutes<10?"0":""}{minutes} : {seconds<10?"0":""}{seconds}</h1>
  }

  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 className="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>
  )
}