import {Component} from 'react'

import { CountryInput } from "./CountryInput.js";
import { Intro } from "./Intro.js";

class Questionaire extends Component {
  state = {
    countries: [
      { code: "ch", name: "China" },
      { code: "in", name: "Indien" },
      { code: "us", name: "Vereinigte Staaten von Amerika" },
      { code: "id", name: "Indonesien" },
      { code: "br", name: "Brasilien" },
      { code: "pk", name: "Pakistan" },
      { code: "ng", name: "Nigeria" },
      { code: "bg", name: "Bangladesch" },
      { code: "ru", name: "Russland" },
      { code: "mx", name: "Mexiko" },
    ],
  };

  render() {
    const rows = this.state.countries.map(
      (row, index) => {
        return (
          <CountryInput key={row.code} country={row}
                        updateCountryBands={this.updateCountryBands.bind(this)} />
        );
      }
    );
    const showTexts = {
      "en": "Show",
      "de": "Aufdecken",
    };
    const showText = showTexts[this.props.lang];
    return (
      <>
        <blockquote id="the-quote">
          I don't need a rationale<br/>
          to sing the Internationale
          <cite>
            They might be giants
          </cite>
        </blockquote>
        <Intro lang={this.props.lang}/>
        <table id="country-list">
          <tbody>
            {rows}
          </tbody>
        </table>
        <button onClick={this.props.show}>
          {showText}
        </button>
      </>
    );
  }

  updateCountryBands(code, bands) {
    console.log(this);
    this.setState({
      bands: {...this.state.bands, [code]: bands}
    });
    fetch(this.props.apiBase + "/update", {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
      body: JSON.stringify({uuid: this.props.uid, country: code, bands: bands}),
    })
    .then((result) => result.json())
    .then((result) => {
      this.setState({apiResult: result });
    })
    .catch((error) => {
      console.log(error);
      this.setState({apiResult: error });
    });
  }

  getCountries() {
    fetch(this.props.apiBase + "/countries/" + this.props.lang, {
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
      }
    )
    .then((result) => result.json())
    .then((result) => {
      this.setState({countries: result});
    })
    .catch((error) => {
      this.setState({apiResult: error });
    })
  }

  componentDidMount() {
    this.getCountries();
  }
}

export {Questionaire};
