import React from 'react'

import client from '../client'

export default class UserList extends React.Component {
  constructor(props){
    super()
    console.log("USER")
    this.state = {
      data: [],
    }
    client.service('users').find({
      query: {
        '$sort': { 'email': '1' },
        token: client.get('token'),
      },
    }).then((data) => {
      this.setState(data)
    }).catch((error) => {
      console.error(error)
    })
    this.pick.bind(this)
    console.log(props)
  }
  pick(user){
    // bubble this up..
    console.log(user)
    console.log(this)
    this.props.updateUser(user)
  }
  render() {
    console.log(this.state.data)
    const items = this.state.data.map((user,i) => {
      return (
        <UserItem key={user.id}
          user={user}
          activeUser={this.props.user}
          onClick={(user) => this.pick(user)}
          onDelete={this.handleDelete} />
      )
    })
    return (
      <div>
        {items}
      </div>
    )
  }
}

class UserItem extends React.Component {
  constructor() {
    super()
    this.remove = this.remove.bind(this)
  }
  remove(e) {
    e.stopPropagation()
    const userid = this.props.user.id
    const usersService = client.service('users')
    const params = { query: { token: client.get('token') } }
    usersService.remove(userid, params).then(result => {
      this.props.onDelete(userid)
    }).catch(error => {
      console.error(error)
    })
  }
  render() {
    const user = this.props.user
    // const canEdit = this.props.user.userid === this.props.currentUser.id ? 'canEdit' : ''
    const userClass = this.props.user.id == this.props.activeUser.id ? 'active' : ''
    const canEdit = 'canEdit'
    const date = parseDate(user.updatedAt)
    const time = parseTime(user.updatedAt)
    return (
      <div className={'user row ' + canEdit} onClick={() => this.props.onClick(this.props.user)}>
        <div className={'email ' + userClass}>{user.email}</div>
        <div className='calories'>{user.goal} cal</div>
        <div className={'role ' + user.role}>{user.role}</div>
        <div className='date'>{date}</div>
        <div className='time'>{time}</div>
        <div className='remove' onClick={this.remove}>x</div>
      </div>
    )
  }
}

function parseDate(d){
  return new Date(d).toISOString().substr(0, 10)
}

function parseTime(d){
  return new Date(d).toISOString().substr(11, 5)
}
