// App.js
import React, { Component } from "react";
import "./App.css";
// import { connect, sendMsg } from "./components/api/index";
import Header from './components/Header';
import Controls from "./components/control/controls";
// import ChatHistory from "./components/ChatHistory/ChatHistory.jsx";

import OpenSeaMap from "./components/OpenSeaMap/OpenSeaMap";
import {w3cwebsocket as W3CWebSocket} from "websocket"

const client = new W3CWebSocket("ws://localhost:8008/");


class App extends Component {
  state =  {
    Entities: [],
    EntityOnFocus: []
  }
  
  componentDidMount() {
   
    client.onopen = () => {
      console.log("Websocket Client for Map Connected");
    };

    client.onmessage = (message) => {
      const dataFromServer = JSON.parse(message.data);
      console.log('reply: ', dataFromServer);

      if(dataFromServer.Type === "COP")
      {
        this.setState((state) => ({
         Entities: dataFromServer.Entities 
        })
        
        )
      }
      
    }

    //   connect((msg) => {
    //       console.log("New Message")
          
    //       var jsonMSG;
    //       try {
    //         jsonMSG = JSON.parse(msg.data);
    //       } catch (error) {
    //         console.log(error);
    //       }
          
    //       if(jsonMSG["Type"] == "COP"){
    //         console.log(msg.data)
    //         var Entities =  Array.from(jsonMSG["Entities"])
    //         if(Array.isArray(Entities))
    //         {
    //           this.setState({
    //             Entities:Entities
    //           });
    //         }
    //       }

  
  
    //   console.log(this.state.Entities);
    // });
    

  }

    updateEntities()
    {
      var msg = 
      {
        Type: "Request",
        Data: "COP"
    
      }
      client.send(JSON.stringify(msg));
    }

    setEntityOnFocus(Entity)
    {
      // console.log(Entity);
      this.setState({
        EntityOnFocus: Entity
      });
    }

  
    
    render() {
    const {name} = this.state;
    return (
      <div className="App">
        <Header />
        <div className="Content">
          
        <Controls Entities= {this.state.Entities} updateEntities = {this.updateEntities} EntityOnFocus = {this.state.EntityOnFocus} />
        {/* <ChatHistory History={this.state.History} /> */}
        {/* <div>
        {name}

        </div> */}
        <OpenSeaMap Entities= {this.state.Entities} updateEntities = {this.updateEntities} setEntityOnFocus = {this.setEntityOnFocus.bind(this)}/>
        </div>
        
        {/* <button onClick={this.send}>Hit</button> */}
      
      </div>
    );
  }
}

export default App;
