import React, { Component } from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import LoginV from './LoginV'

/*  Add a field to the state of this component that is a boolean that determines if he is sign in or not. */
class LoginC extends Component {
  constructor (props) {
    super(props)
    this.state = {
      email: '',
      password: ''
    }
  }

  onChangeEmail = (evt) => {
    this.setState({
      email: evt.target.value
    })
  }

  onChangePassword = (evt) => {
    this.setState({
      password: evt.target.value
    })
  }

  submitForm = (event) => {
    event.preventDefault()

    let data = {
      email: this.state.email,
      password: this.state.password
    }
    let url = 'http://localhost:4000/login'
    axios.post(url, data)
      .then(res => {
        sessionStorage.setItem('token', res.data.token)
        sessionStorage.setItem('userID', res.data.userID)
        sessionStorage.setItem('userRole', res.data.userRole)
        const UserData = {
          newToken: res.data.token,
          id: res.data.userID,
          role: res.data.userRole
        }
        this.props.stateHandler(UserData)
      })
      .catch(err => {
        console.log(err)
      })
  }

  render () {
    return (
      <LoginV email={this.state.email}
        password={this.state.password}
        changeEmail={this.onChangeEmail}
        changePassword={this.onChangePassword}
        submit={this.submitForm} />
    )
  }
}

LoginC.propTypes = {
  stateHandler: PropTypes.func
}

export default LoginC
