import React, { Component } from 'react';
import './App.css';
import Tables from './Tables';


class App extends Component {
  constructor(props){
    super(props);
    this.apiUrl = "http://192.168.17.94:9876";
    this.name = null;
    this.state = {
      persons: []
    };
    
    this.componentDidMount = this.componentDidMount.bind(this)
  }

  // is called once when loading the page
  componentDidMount() {
    this.reloadLocations();
    setInterval(this.updateLocation, 10000);
  }
  
  reloadLocations = () => {
    fetch(this.apiUrl + "/users")
      .then(response => response.json())
      .then(data =>{
         console.log(data["users"]);
         this.setState({ persons: data["users"] })
      }).catch(error => {
        console.log(error);
    });
  }
  
  receivedPosition = (position) => {
    const axios = require('axios');
    axios.put(this.apiUrl + "/report-location", {
      "longitude": position.coords.longitude + Math.random()*10,
      "latitude": position.coords.latitude,
      "timestamp": position.timestamp/1000, // in seconds
      "name": this.name
    }).then(this.reloadLocations)
    .catch(error => {
        console.log(error);
    });
  }
  
  updateLocation = () => {
    if (this.name!=null && navigator.geolocation) { //check if geolocation is available
      navigator.geolocation.getCurrentPosition(this.receivedPosition);
    }
  }
  

  render (){
    return (
      <div id="wrapper">
        <Tables persons={this.state.persons}/>

        <button
            onClick={ () => {
              this.name = "Bernie";
            }}> Bernie </button>
        <button
            onClick={ () => {
              this.name = "Martin";
            }}> Martin </button>
        <button
            onClick={ () => {
              this.name = "Simon";
            }}> Simon </button>
        <button
            onClick={ () => {
              this.name = "Lukas";
            }}> Lukas </button>
      </div>
  );
  }
}



export default App;
