import {Component} from 'react'

class Stats extends Component {
  state = {
    stats: {
      countries: []
    }
  };
  render() {
    console.log("in Stats.render");
    console.log("in Stats.render: stats = ", this.state.stats);
    let rows = [];
    for (let country of this.state.stats.countries) {
      let bands = []
      let k=0
      for (let band of country.bands) {
        k++;
        let n;
        if (band.by_user) {
          n = <span key={k} className="band by_user">{band.name}</span>
        } else {
          n = <span key={k} className="band">{band.name}</span>
        }
        if (bands.length > 0) {
          bands.push(", ")
        }
        bands.push(n)
      }
      rows.push(<tr key={country.code}><th>{country.name}</th><td>{bands}</td></tr>);
    }

    let summary;
    if (this.props.lang == "de") {
      summary = (
        <p id="summary">
          Du hast Bands aus {this.state.stats.country_count} Ländern genannt,
          Damit bist Du auf Platz {this.state.stats.country_rank} von {this.state.stats.user_count}.
        </p>
      );
    } else if (this.props.lang == "en") {
      summary = (
        <p id="summary">
          You submitted bands from {this.state.stats.country_count} countries,
          which puts you at place {this.state.stats.country_rank} of {this.state.stats.user_count}.
        </p>
      );
    }
    const linkSymbol = "\u{1F517}\u{FE0E}"
    return [
      <div id="permalink"><a href={"/stats/" + this.props.puid}>{linkSymbol} Permalink</a></div>,
      summary,
      <table id="country-list">{rows}</table>
    ];
  }

  componentDidMount() {
    console.log("in componentDidMount")
    fetch(this.props.apiBase + `/stats/${this.props.puid}/${this.props.lang}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
    })
    .then((result) => result.json())
    .then((result) => {
      this.setState({stats: result });
    })
    .catch((error) => {
      console.log(error);
      this.setState({apiResult: error });
    });
  }
}

export {Stats};
