import { h, Component } from 'preact';

import { startCase, bindAll } from 'lowline';

import timeFilter from '../util/time-filter';

export default class Timer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      time: props.time,
      totalTime: props.time,
      startTime: undefined,
    };

    bindAll(this, ['start', 'pause', 'reset', 'updateTimer', 'end']);
  }

  componentDidMount() {
    this.reset();
  }

  start() {
    this.setState({
      startTime: Date.now(),
    });

    this.interval = setInterval(this.updateTimer, 10);
  }

  pause() {
    clearInterval(this.interval);
  }

  reset() {
    clearInterval(this.interval);

    this.setState({
      time: this.props.time,
      totalTime: this.props.time,
      startTime: undefined,
    });
  }

  updateTimer() {
    let time = this.state.totalTime - (Date.now() - this.state.startTime);

    if (time <= 0) {
      this.pause();

      this.end();

      time = 0;
    }

    document.title = timeFilter(time).slice(0, 5);

    this.setState({
      time,
    });
  }

  end() {
    const data = {
      startTime: this.state.startTime,
      endTime: new Date(),
      type: this.props.type,
      length: this.props.time,
    };

    document.title = 'Pling!';

    if (Notification.permission !== 'granted') {
      Notification.requestPermission();
    } else {
      const title = this.props.type === 'pomodoro' ? 'Pomodoro Complete!' : 'Break is over!';
      const body = this.props.type === 'pomodoro' ? 'Time for a break!' : 'Get back to work!';
      const notification = new Notification(title, {
        icon: 'https://www.planetnatural.com/wp-content/uploads/2014/03/tomato-supplies.jpg',
        body,
      });
    }

    fetch('/api/pomodoros', {
      method: 'POST',
      body: JSON.stringify(data),
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then((response) => response.json())
      .then((json) => {
        console.log('succes');
      });
  }

  render(props, state) {
    return (
      <section class="timer">
        <h1>{startCase(props.type)}</h1>

        <div class="time">{timeFilter(state.time || 0)}</div>
        <div class="buttons">
          <button onClick={this.start}>Start</button>
          <button onClick={this.reset}>Reset</button>
        </div>
      </section>
    );
  }
}
