import React from 'react'

class ConfigList extends React.Component {
  constructor() {
    super()
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange (event) {
    event.preventDefault()
    const { configChangeForm } = this.props.configActions
    const nextConfig = {
      _id: this.configid ? this.configid.value : null,
      key: this.key.value,
      description: this.description.value,
      value: this.value.value
    }
    configChangeForm(nextConfig)
  }

  render () {
    const state = this.props.config
    const actions = this.props.configActions
    const config = state.configForm

    return (
      <div>
        <form>
          <h2>{(config._id) ? "Konfiguration editieren" : "Neue Konfiguration"}</h2>
          {config._id ? <input type="hidden" key="configid" value={config._id} ref={(input) => {this.configid = input}} id="configid"/> : null}
          <label htmlFor="key">Schluessel</label>
          <input type="input" ref={(input) => {this.key = input}} id="key" value={config.key} placeholder="Schluessel" onChange={this.handleChange} readOnly={!!config._id}></input>
          <label htmlFor="description">Beschreibung</label>
          <input type="input" ref={(input) => {this.description = input}} id="description" value={config.description} placeholder="Beschreibung" onChange={this.handleChange}></input>
          <label htmlFor="value">Wert</label>
          <input type="input" ref={(input) => {this.value = input}} id="value" value={config.value} placeholder="Wert" onChange={this.handleChange}></input>
          <input type="submit" value={config._id ? "Aenderungen speichern" : "Konfiguration anlegen"} onClick={(event) => {
              event.preventDefault()
              if (config._id) {
                actions.configEditRequest(config)
              } else {
                actions.configAddRequest(config)
              }
            }} />
          <input type="reset" value={config._id ? "Abbrechen" : "Loeschen"} onClick={(event) => {
              event.preventDefault()
              actions.configClearForm(event)
            }} />
        </form>
        <table className='table table-bordered table-striped'>
          <thead>
            <tr>
              <th>Schluessel</th><th>Beschreibung</th><th>Wert</th><th>Wert</th>
            </tr>
          </thead>
          <tbody>
            {state.configs ? state.configs.map((configData, key) => 
            <tr key={key}>
              <td>{configData.key}</td>
              <td>{configData.description}</td>
              <td>{configData.value}</td>
              <td>
                <a href="#" onClick={(event) => actions.configLoadForm(key)}>editieren</a>
                <a href="#" onClick={(event) => actions.configDeleteRequest({key: configData.key})}>loeschen</a>
              </td>
            </tr>
            ) : ""}
          </tbody>
        </table>
      </div>
    )
  }
}

export default ConfigList
