import { h, Component } from 'preact';

import { bindAll } from 'lowline';

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

const length = 25 * 60 * 1000;

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

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

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

  componentDidMount() {
    this.reset();
  }

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

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

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

  reset() {
    clearInterval(this.interval);

    this.setState({
      time: length,
      totalTime: length,
      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(),
    };

    document.title = 'Pling!';

    if (Notification.permission !== 'granted') {
      Notification.requestPermission();
    } else {
      const notification = new Notification('Pomodoro complete!', {
        icon: 'https://www.planetnatural.com/wp-content/uploads/2014/03/tomato-supplies.jpg',
        body: 'Time for a break!',
      });
    }

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

  render(props, state) {
    return (
      <div class="timer">
        <div class="time">{timeFilter(state.time || 0)}</div>
        <div class="buttons">
          <button onClick={this.start}>Start</button>
          <button>Pause</button>
          <button>Reset</button>
        </div>
      </div>
    );
  }
}
