import {Component} from 'react'

class CountryInput extends Component {
  state = {
    bands: []
  };
  render() {
    let bandInputs = [];
    for (let i = 0; i <= this.state.bands.length; i++) { // sic!
      const id = `${this.props.country.code}/${i}`;
      const value = this.state.bands[i] || "";
      bandInputs[i] = <input key={i} id={id} value={value}
                             onChange={this.handleChange}
                             onBlur={this.handleBlur} />
    }
      
    return (
      <tr key={this.props.country.code}>
        <th> {this.props.country.name} </th>
        <td> {bandInputs} </td>
      </tr>
    );
  }

  handleChange = (e) => {
    const id = e.target.id;
    const i = +id.split("/")[1];
    let newBands = [];
    newBands[i] = e.target.value;
    for (let j = 0; j < this.state.bands.length; j++) {
      if (i !== j) {
        newBands[j] = this.state.bands[j];
      }
    }
    this.setState({bands: newBands});
  }

  handleBlur = (e) => {
    console.log(e);
    this.props.updateCountryBands(this.props.country.code, this.state.bands);
  }

}

export {CountryInput};
