'use strict'

class Transport {
  constructor (length) {
    this._length = length
    this._startTime = Date.now() / 1000
    this._playHeadPosition = 0
    this._isPlaying = true
  }
  seekExact (time) {
    this._playHeadPosition = Math.max(0, time);
    this._startTime = Date.now() / 1000 - this._playHeadPosition;
  }
  seekDelta(time) {
    const newPlayHeadTime = Math.max(0, this._playHeadPosition + time);
    this._startTime += this._playHeadPosition - newPlayHeadTime;
    this._playHeadPosition = newPlayHeadTime;
  }
  update () {
    if (this._isPlaying) {
      const timeNow = Date.now() / 1000
      this._playHeadPosition = timeNow - this._startTime
    }
    if (this._playHeadPosition > this._length) {
      this._playHeadPosition = this._length
      if (this.getIsPlaying()) {
        this.setIsPlaying(false)
      }
    }
  }
  getIsPlaying () {
    return this._isPlaying
  }
  setIsPlaying(isPlaying) {
    if (!this._isPlaying && isPlaying) {
      const timeNow = Date.now() / 1000;
      this._startTime = timeNow - this._playHeadPosition;
    }
    this._isPlaying = isPlaying;
  }
  getCurrentTime () {
    return this._playHeadPosition
  }
  getLength () {
    return this._length
  }
}
