<template>
  <div class="hotpay-video">
    <hotpay-subtitle :data="data.title" />

    <div class="hotpay-video-container" :class="data.size">
      <hotpay-facebook :data="facebookVideoData" v-if="hasFacebookLink" />
      <iframe :src="videoUrl" frameborder="0" allowfullscreen v-else></iframe>
      <div class="hotpay-video-wrapper"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  @import '../stylesheets/variables.scss';

  .hotpay-video {
    margin-bottom: 24px;
  }

  .hotpay-video-container {
    position: relative;

    &.large {
      width: 100%;
    }

    &.medium {
      width: 75%;
    }

    &.small {
      width: 50%;
    }
  }

  .hotpay-video-wrapper {
    padding: 25px 0 56.25%;
    width: 100%;
  }

  iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
</style>

<script>
  import getVideoId from 'get-video-id'
  import HotpaySubtitle from '../HotpaySubtitle/HotpaySubtitle'
  import HotpayFacebook from '../HotpayFacebook/HotpayFacebook'

  export default {
    name: 'hotpay-video',
    components: {
      HotpaySubtitle,
      HotpayFacebook
    },
    props: {
      data: Object
    },
    data: () => ({
      hasFacebookLink: false
    }),
    computed: {
      videoMeta () {
        return getVideoId(this.data.url)
      },
      videoUrl () {
        if (this.videoMeta) {
          if (this.videoMeta.service === 'youtube') {
            return this.getYoutubeUrl()
          }

          if (this.videoMeta.service === 'vimeo') {
            return this.getVimeoUrl()
          }
        }

        if (this.data.url.indexOf('facebook') >= 0) {
          this.hasFacebookLink = true
        }

        return this.data.url
      },
      facebookVideoData () {
        return {
          type: 'video',
          options: {
            url: this.data.url,
            width: this.data.width,
            showText: !this.data.hideDetails
          }
        }
      }
    },
    methods: {
      getYoutubeUrl () {
        let videoUrl = `https://www.youtube.com/embed/${this.videoMeta.id}?`

        if (this.data.hideControls) {
          videoUrl += '&controls=0'
        }

        if (this.data.hideDetails) {
          videoUrl += '&showinfo=0'
        }

        if (this.data.autoplay) {
          videoUrl += '&autoplay=1'
        }

        return videoUrl
      },
      getVimeoUrl () {
        let videoUrl = `https://player.vimeo.com/video/${this.videoMeta.id}`

        if (this.data.hideDetails) {
          videoUrl += '?title=0&byline=0&portrait=0'
        }

        if (this.data.autoplay) {
          videoUrl += '&autoplay=1'
        }

        return videoUrl
      }
    }
  }
</script>
