/**
 * 1.0
 * plyr soundcloud plugin
 * 
 * @ flatfull.com All Rights Reserved.
 * Author url: flatfull.com
 */

function triggerEvent(element, type = '', bubbles = false, detail = {}) {
  if ( ! (element !== null &&
    typeof element === 'object' &&
    element.nodeType === 1 &&
    typeof element.style === 'object' &&
    typeof element.ownerDocument === 'object') || type == '' ) {
      return;
  }
  // Create and dispatch the event
  detail.plyr = this;
  var event = new CustomEvent(type, {
    bubbles,
    detail
  });

  // Dispatch the event
  element.dispatchEvent(event);
}

function assurePlaybackState(play) {
  if (play && !this.embed.hasPlayed) {
    this.embed.hasPlayed = true;
  }
  if (this.media.paused === play) {
    this.media.paused = !play;
    triggerEvent.call(this, this.media, play ? 'play' : 'pause');
  }
}

var soundcloud = {
  setup() {
    var player = this;

    player.elements.wrapper.classList.add(player.config.classNames.embed);

    player.config.urls.soundcloud = 'https://w.soundcloud.com/player/?url=';
    if (typeof window.SC !== 'object') {
      soundcloud.loadScript.call(player);
    } else {
      soundcloud.ready.call(player);
    }
  },
  ready(){
    var player = this;
    var source = player.media.getAttribute('src');

    var iframe = document.createElement('iframe');
    var src = player.config.urls.soundcloud + source +'&auto_play=true';
    iframe.setAttribute('src', src);
    iframe.setAttribute(
      'allow',
      ['autoplay'].join('; '),
    );

    player.media = player.media.parentNode.replaceChild(iframe, player.media);

    player.embed = SC.Widget(iframe);

    player.embed.bind(SC.Widget.Events.READY, function() {
      player.media.play = function(){
        assurePlaybackState.call(player, true);
        player.embed.play();
      };

      player.media.pause = function(){
        assurePlaybackState.call(player, false);
        player.embed.pause();
      };

      player.media.stop = function(){
        player.embed.seekTo(0);
        player.embed.pause();
        player.media.paused = true;
      };

      player.media.paused = true;
      player.media.currentTime = 0;
      player.options.speed = [1];

      var currentSrc;
      player.embed.getCurrentSound(function(value){
        currentSrc = value.uri;
      });

      Object.defineProperty(player.media, 'currentSrc', {
        get() {
          return currentSrc;
        },
      });

      // Seeking
      var currentTime = 0, currentPosition;
      Object.defineProperty(player.media, 'currentTime', {
        get() {
          return currentTime;
        },
        set(time) {
          player.media.seeking = true;
          triggerEvent.call(player, player.media, 'seeking');
          player.embed.seekTo(time * 1000);
        },
      });

      // volume
      Object.defineProperty(player.media, 'volume', {
        get() {
          return player.config.volume;
        },
        set(input) {
          player.embed.setVolume(input*100);
          player.config.volume = input;
          triggerEvent.call(player, player.media, 'volumechange');
        },
      });
      // muted
      Object.defineProperty(player.media, 'muted', {
        get() {
          return player.config.muted;
        },
        set(input) {
          var toggle = (typeof input == 'boolean') ? input : false;
          player.embed.setVolume(toggle ? 0 : player.config.volume * 100);
          player.config.muted = toggle;
          triggerEvent.call(player, player.media, 'volumechange');
        },
      });

      Object.defineProperty(player.media, 'ended', {
        get() {
          return player.currentTime === player.duration;
        },
      });

      player.embed.bind(window.SC.Widget.Events.PLAY, function(){
        assurePlaybackState.call(player, true);
        triggerEvent.call(player, player.media, 'playing');
      });

      player.embed.bind(window.SC.Widget.Events.PAUSE, function(){
        assurePlaybackState.call(player, false);
      });

      player.embed.bind(window.SC.Widget.Events.LOAD_PROGRESS, function(data) {
          player.media.buffered = data.loadProgress;
          triggerEvent.call(player, player.media, 'progress');
          if (parseInt(data.loadProgress) === 1) {
            triggerEvent.call(player, player.media, 'canplaythrough');
          }
      });

      player.embed.bind(window.SC.Widget.Events.PLAY_PROGRESS, function(data) {
          player.media.seeking = false;
          currentPosition = parseInt(data.currentPosition / 1000);
          if(currentPosition > player.media.currentTime || currentPosition == 0  ){
            currentTime = currentPosition;
            triggerEvent.call(player, player.media, 'timeupdate');
            player.embed.getDuration(function(value){
              player.media.duration = value/1000;
              triggerEvent.call(player, player.media, 'durationchange');
            });
          };
      });

      player.embed.bind(window.SC.Widget.Events.FINISH, function() {
          player.media.paused = true;
          triggerEvent.call(player, player.media, 'ended');
      });

      setTimeout( function(){ window.Plyr.ui.build.call(player) }, 0);

    });

  },
  loadScript(){
    var player = this;
    var script = document.createElement('script');
    script.onload = function () {
        soundcloud.ready.call(player);
    };
    script.src = 'https://w.soundcloud.com/player/api.js';
    document.head.appendChild(script);
  }
}
