import React, {Component} from 'react'
import {v4 as uuidv4} from 'uuid';

import './App.css';

import { Questionaire } from "./Questionaire.js";
import { Stats } from "./Stats.js";

const apiBase = "http://localhost:8000";

class App extends Component {
  state = {
    screen: "questionaire",
    uid: uuidv4(),
    lang: this.getPreferredLanguage(),
  };
  render() {
    console.log(this.state.screen);
    let screen = false;
    if (this.state.screen == "questionaire") {
      screen = <Questionaire uid={this.state.uid} lang={this.state.lang}
                             show={this.showStats.bind(this)}
                             apiBase={apiBase} />
    } else if (this.state.screen == "stats") {
      screen = <Stats puid={this.state.uid.substr(24)} lang={this.state.lang} apiBase={apiBase} />
    } else {
      screen = <div className="error">Impossible</div>
    }
    return (
      <div className="App">
        {screen}
      </div>
    )
  }

  getPreferredLanguage() {
    const availableLanguages = ["en", "de"];
    for (let lng of navigator.languages) {
      const preferredLanguage = availableLanguages.find(x => lng.startsWith(x));
      if (preferredLanguage) {
        return preferredLanguage;
      }
    }
    return availableLanguages[0];
  }

  showStats() {
    console.log("in showStats");
    this.setState({screen: "stats"});
  }

  componentDidMount() {
    console.log("in componentDidMount");
    console.log("window.location", window.location);
    const pm = window.location.pathname.match("^/(stats)/([0-9a-f]+)");
    if (pm) {
      this.setState({screen: pm[1], uid: "00000000-0000-0000-0000-" + pm[2]})
    }
  }
}

export default App;
