import React from 'react'
import LoggedOutView from './LoggedOutView.jsx'
import MealView from './MealView.jsx'

import client from '../client'

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      ready: false,
      loggedIn: false,
      user: {},
    }
    client.authenticate()
      .then(user => {
        this.setState({
          ready: true,
          loggedIn: true,
          user: user.data
        })
      })
      .catch(error => {
        this.setState({ ready: true })
        console.error(error)
      })
  }
  logOut() {
    this.setState({
      user: null,
      loggedIn: false,
    })
  }
  render() {
    if (this.state.ready) {
      if (this.state.loggedIn) {
        return (
          <MealView user={this.state.user} />
        )
      }
      else {
        return (
          <LoggedOutView />
        )
      }
    }
    else {
      return (
        <div>Loading...</div>
      )
    }
  }
}

