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

import feathers from 'feathers/client'
import feathersHooks from 'feathers-hooks'
import feathersRest from 'feathers-rest/client'
import feathersAuthentication from 'feathers-authentication/client'
import superagent from 'superagent'

const rest = feathersRest(window.location.origin)

const client = feathers()
              .configure(feathersHooks())
              .configure(feathersAuthentication({ storage: localStorage }))
              .configure(rest.superagent(superagent))

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

