import React, { Component } from 'react';
import LetterOptions from './LetterOptions';
import Button from './Button';
import Preview from './Preview';
import LatestList from './LatestList';
import {generatePdf, getLatest, removeLatest} from './apiHelper';

//import './App.css';

class App extends Component {
  componentDidMount() {
    this._getLatest();
  }

  render() {
    const state = this.state || {};

    return (
      <div className="home">
        <div>
          <LetterOptions onChange={this._onChange.bind(this)} {...state.options}/>
          <LatestList latest={state.latest} onSelect={this._onSelectLatest.bind(this)}
            onRemove={this._onRemoveLatest.bind(this)}
          />
        </div>
        <div>
          <div>
            <Button onClick={this._onGenerate.bind(this)}>Backe PDF</Button>
            <Button onClick={this._onClear.bind(this)}>Alles Löschen</Button>
          </div>
          <Preview
            pdfUrl={state.pdfUrl}
            pdfIsLoading={state.pdfIsLoading}
            pdfError={state.pdfError}
          />
        </div>
      </div>
    );
  }

  _onSelectLatest(selectedOptions) {
    this.setState({options: Object.assign({}, selectedOptions)});
  }

  _onRemoveLatest(item) {
    removeLatest(item)
      .then(() => {
        const latest = this.state.latest
          .filter(curr => curr.id !== item.id);

        this.setState({ latest });
      });
  }

  _onClear() {
    window.location.reload();
  }

  _onGenerate() {
    const state = this.state || {};
    this.setState({
      pdfIsLoading: true,
      pdfError: null
    })

    generatePdf(state.options)
      .then((data) => {
        const {id} = data;
        this.setState({
          pdfIsLoading: false,
          pdfUrl: `/api/pdf/${id}`
        });
      })
      .catch((error) => {
        this.setState({
          pdfIsLoading: false,
          pdfError: error.message,
          pdfUrl: null
        });
      })
      .then(() => this._getLatest())
  }

  _getLatest() {
    getLatest()
      .then(latest => this.setState({latest}))
      .catch(err => console.error('Unable to get latest:', err));
  }

  _onChange(name, event) {
    if (!name) {
      return;
    }
    const value = event && event.target && event.target.value;
    const options = Object.assign({}, this.state.options, {[name]: value || undefined});
    this.setState({options});
  }
}

export default App;
