import React from 'react'
import { DateRange } from 'react-date-range';
import moment from 'moment'
import client from '../client'

export default class MealFilter extends React.Component {
  constructor(){
    super()

    const start = new Date ()
    start.setHours(0)
    start.setMinutes(0)
    start.setSeconds(0)
    start.setDate(start.getDate()-6)

    const end = new Date ()
    end.setHours(23)
    end.setMinutes(59)
    end.setSeconds(59)

    this.state = {
      startDate: moment(start),
      endDate: moment(end),
      startTime: 0,
      endTime: 23,
      meals: [],
    }
    this.handleSelect = this.handleSelect.bind(this)
    this.fetch = this.fetch.bind(this)
    this.filter = this.filter.bind(this)
  }
  fetch (state){
    state = state || this.state
    let start = state.startDate
    let end = state.endDate

    client.service('meals').find({
      query: {
        userid: this.props.user.id,
        date: { $gte: start.toDate(), $lte: end.toDate() },
        $sort: { 'date': '-1' },
        token: client.get('token'),
      },
    }).then((data) => {
      this.setState({meals: data.data})
      this.filter(data.data)
    }).catch((error) => {
      console.error(error)
    })
  }
  filter(meals, state) {
    meals = meals || this.state.meals
    state = state || this.state
    const start = state.startTime
    const end = state.endTime
    const filteredMeals = this.state.meals.filter((meal) => {
      const hours = new Date(meal.date).getHours()
      return (start <= hours && hours <= end)
    })
    this.props.onChange(filteredMeals)
  }
  handleSelect(range){
    const start = range.startDate
    start.hours(0)
    start.minutes(0)
    start.seconds(0)

    const end = start.isSame(range.endDate) ? start.clone() : range.endDate
    end.hours(23)
    end.minutes(59)
    end.seconds(59)

    this.setState({
      startDate: start,
      endDate: end,
    })
    this.fetch({
      startDate: start,
      endDate: end,
    })
  }
  pickTimeRange(event,start,end){
    this.setState({startTime: start, endTime: end})
    this.filter(this.state.meals, {startTime: start, endTime: end})
  }

  render(){
    var times = [
      [0, 11, 'Breakfast'],
      [12, 15, 'Lunch'],
      [16, 23, 'Dinner'],
      [0, 23, 'All'],
    ].map( (r,i) => {
      const start = r[0]
      const end = r[1]
      const name = r[2]
      let className = ''
      if (this.state.startTime === start && this.state.endTime === end) {
        className = 'selected'
      }
      return (
        <button
          key={i}
          className={className}
          onClick={(e) => {this.pickTimeRange(e,start,end)}}>
          {name}
        </button>
      )
    })
    return (
      <div>
        <DateRange
          onInit={this.handleSelect}
          onChange={this.handleSelect}
          startDate={this.state.startDate}
          endDate={this.state.endDate}
        />
        {times}
      </div>
    )
  }
}
