// 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 config = {
  // apiUrl: process.env.REACT_APP_WEBAPP_WS_URL,
  apiUrl: "192.168.3.13",
  apiProt: 30747
}

// const config = {
//   // apiUrl: process.env.REACT_APP_WEBAPP_WS_URL,
//   apiUrl: "localhost",
//   apiProt: 9999
// }


const client = new W3CWebSocket("ws://"+config.apiUrl+":"+config.apiProt+"/");


class App extends Component {
  state =  {
    Entities: [],
    EntityOnFocus: []
  }
  
  componentDidMount() {
   console.log(config.apiUrl);

    client.onopen = () => {
      console.log("Websocket Client for Map Connected");
    };

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

      if(dataFromServer.Data === "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} />
       
        <OpenSeaMap Entities= {this.state.Entities} updateEntities = {this.updateEntities} setEntityOnFocus = {this.setEntityOnFocus.bind(this)}/>
        </div>
        
      
      </div>
    );
  }
}

export default App;
