import templateEngine from '@pluginjs/template'
import $ from 'jquery'
import Pj from '@pluginjs/pluginjs'
import { events as EVENTS } from '../constant'

window.AsVimeoAPIReady = false

class Vimeo {
  constructor (video, element, options) {
    this.element = element
    this.options = options
    this.video = video
    this.classes = video.classes
  }

  load () {
    this.$wrap = $(this.createHtml())
    this.$wrap.appendTo(this.element)
    if (this.options.poster) {
      this.$poster = this.$wrap.find(`.${this.video.classes.POSTER}`)
      this.$poster.css({ 'background-image': `url(${this.options.poster})` })
    }

    if (window.AsVimeoAPIReady) {
      this.init()
      this.video.trigger(EVENTS.LOAD)
    } else {
      this.loadApi()
      Pj.$window.on('AsVideoVimeoAPIReady', () => {
        this.init()
        this.video.trigger(EVENTS.LOAD)
      })
    }
  }

  init () {
    const playerSettings = {
      id: this.getId(),
      loop: this.options.loop,
      autoplay: this.options.autoplay,
      // height:400,
      // url:'https://player.vimeo.com/video/76979871',
      title: false, // defaults to true
      portrait: false, // Show the user’s portrait on the video. Defaults to true.
      // maxwidth: '',
      // maxheight '',
      xhtml: false, // Make the embed code XHTML compliant. Defaults to false.
      byline: false, // Show the byline on the video. Defaults to true.
      autopause: false // Pause this video automatically when another one plays. Defaults to true.
    }

    this.media = new window.Vimeo.Player(this.$wrap[0], playerSettings)
    this.bind()
  }

  getId () {
    if (this.options.id) {
      return this.options.id
    } else if (this.options.url) {
      return this.options.url.split('/')[3].split('?')[0]
    }
    return undefined
  }

  createHtml () {
    let poster = ''

    if (this.options.poster !== '') {
      poster = templateEngine.render(this.options.templates.poster.call(this), { classes: this.classes })
    }

    const html = templateEngine.render(this.options.template.call(this), {
      classes: this.classes,
      poster
    })
    return html
  }

  loadApi () {
    const tag = document.createElement('script')
    tag.src = 'https://player.vimeo.com/api/player.js'
    document.querySelector('body').appendChild(tag)

    const event = document.createEvent('Event')
    event.initEvent('AsVideoVimeoAPIReady', true, true)
    let count = 1
    const vimeoApiReady = setInterval(() => {
      if (count > 50) {
        clearInterval(vimeoApiReady)
        console.log('loadApi error')
        this.video.destroy()
      }
      count++
      if (typeof window.Vimeo === 'undefined') {
        return
      }
      window.AsVimeoAPIReady = true
      window.dispatchEvent(event)
      clearInterval(vimeoApiReady)
    }, 350)
  }

  bind () {
    this.media.on('play', () => {
      this.video.trigger(EVENTS.PLAY)
    })
    this.media.on('pause', () => {
      this.video.trigger(EVENTS.PAUSE)
    })
    this.media.on('loaded', () => {
      this.video.trigger(EVENTS.LOADED)
      if (this.options.poster) {
        this.$poster.hide()
      }
    })
  }

  setSize (width, height) {
    this.$wrap.css('width', width)
    this.$wrap.css('height', height)
  }

  switchVideo (id) {
    this.media.loadVideo(id)
  }

  _currentTime () {
    this.media.getCurrentTime().then(seconds => {
      this.options.currentTime = seconds
    })
  }

  currentTime () {
    this._currentTime()
    return this.options.currentTime
  }

  _duration () {
    return this.media.getDuration().then(duration => {
      this.options.duration = duration
    })
  }

  duration () {
    this._duration()
    return this.options.duration
  }

  setCurrentTime (val) {
    this.media.setCurrentTime(val)
  }

  stop () {
    this.media.setCurrentTime(0)
    this.media.pause()
    this.video.trigger(EVENTS.STOP)
  }

  mute () {
    this.volume(0)
  }

  unMute () {
    this.volume(50)
  }

  pause () {
    this.media.pause()
    this.video.trigger('pause')
  }

  volume (value) {
    this.media.setVolume(value / 100)
  }

  play () {
    this.media.play()
  }

  destroy () {
    const element = this.$wrap.find('iframe')
    if (element.length) {
      element[0].src = '//about:blank'
    }
    this.$wrap.remove()
  }
}

export default Vimeo
