import config from "@/config";
import { IsWechat } from "./platform";

Howler._unlockAudio();
// Howl.prototype.setSRC = function(newSrc) {

//     var self = this;
//     self.stop();
//     self._src = newSrc;
//     self._sprite = {};
//     self._duration = 0;
//     if (self._sounds[0] && self._sounds[0]._node) {
//         self._sounds[0]._node.src = newSrc;
//     }
//     self.load();
// }

let isReady = false;
export const checkReadyToPlay = function(resolve, isTouchToPlay) {
  
  if (isReady === true) {
    return resolve();
  }

  try {
    function ready() {
      if (typeof parent.WeixinJSBridge !== "undefined") {
        console.log("wx play");
        parent.WeixinJSBridge.invoke(
          "getNetworkType",
          {},
          function(e) {
            resolve((isReady = true));
          },
          false
        );
      } else if (isTouchToPlay) {
        resolve((isReady = true));
        document.querySelector("body").removeEventListener("touchend", ready);
        document.querySelector("#player") && document.querySelector("#player").removeEventListener("touchend", ready);
      }
    }
    if (config.isMobile) {
      if (IsWechat) {
        if (typeof parent.WeixinJSBridge !== "undefined") {
          ready();
        } else {
          parent.document.addEventListener("WeixinJSBridgeReady", ready);
        }
      } else if (isTouchToPlay) {
        document.querySelector("body").addEventListener("touchend", ready);
        document.querySelector("#player") && document.querySelector("#player").addEventListener("touchend", ready);
        ready();
      }
    } else {
      resolve((isReady = true));
    }
  } catch (error) {
    resolve((isReady = true));
  }
};

class SoundPlayer extends EventEmitter {
  constructor(options = {}) {
    super();
    this._pause_byother = false;
    this._disable = false;
    this._canplay = false;
    this._options = options;
    // this._sound = new Howl({
    //     src: [''],
    //     loop: options.loop ? true : false,
    //     html5: options.html5 ? true : false,
    //     format: ['mp3', 'webm'],
    // })

    // this._sound.on('play', () => this.emit('play'))
    // this._sound.on('end', () => this.emit('end') && this.emit('off'))
    // this._sound.on('pause', () => this.emit('pause') && this.emit('off'))
    // this._sound.on('stop', () => this.emit('stop') && this.emit('off'))
    // this._sound.on('loaderror', err => this.emit('error', err))

    // if (!options.html5) {
    //     this._sound.on('load', () => {
    //         this.emit('loaded', this._sound.duration())
    //     })
    // }
  }
  init(src) {
    this.remove();
    this._canplay = true;
    this._sound = new Howl({
      src: [src],
      loop: this._options.loop ? true : false,
      html5: this._options.html5 ? true : false,
      //preload : this._options.html5 ? true : false,
      format: ["mp3", "webm"],
    });

    this._sound.on("play", () => this.emit("play"));
    this._sound.on("end", () => this.emit("end") && this.emit("off"));
    this._sound.on("pause", () => this.emit("pause") && this.emit("off"));
    this._sound.on("stop", () => this.emit("stop") && this.emit("off"));
    this._sound.on("loaderror", (err) => this.emit("error", err));

    this._sound.once("load", () => {
      this.emit("loaded", this._sound.duration());
    });
  }
  /**
   * 设置播放源
   * @param {String} src 音频地址
   * @param {Boolean} isAutoplay 是否自动播放,default:true
   */
  setSRC(src) {
    //this._sound.setSRC(src)
    //this._pause_byother = false

    if (src) {
      this.init(src);
    } else {
      this.remove();
      //this.emit('stop') && this.emit('off')
    }
  }
  /**
   * 设置是否循环
   * @param {Boolean} isLoop
   */
  setLoop(isLoop) {
    if (!this._canplay) {
      return;
    }
    this._sound.loop(isLoop);
  }
  /**
   * 播放
   */
  play() {
    setTimeout(() => {
      if (this._disable || !this._canplay || this._sound.playing()) {
        return;
      }

      this._sound.play();
      this._pause_byother = false;
    }, 10);
  }
  /**
   * 停止
   */
  stop() {
    if (!this._canplay) {
      return;
    }
    if (!this._sound.playing()) {
      return;
    }
    this._sound.stop();
  }
  /**
   * 暂停
   * @param {Boolean} isByOther 是否由其他播放源导致的暂停，default:false
   */
  pause(isByOther = false) {
    if (!this._canplay) {
      return;
    }
    if (this._sound.playing()) {
      this._sound.pause();
      this._pause_byother = isByOther;
    }
  }
  /**
   * 强制标记为其他播放源引起的暂停行为
   */
  pauseByOther() {
    if (this._canplay) {
      this._pause_byother = true;
    }
  }
  time(time) {
    if (!this._canplay) {
      return;
    }
    this._sound.seek(time);
  }
  /**
   * 设置静音
   */
  mute(muted) {
    if (!this._canplay) {
      return;
    }
    this._sound.mute(muted);
  }
  /**
   * 继续播放（如果pause方法中的isByOther为true，则可以继续播放，否则无效）
   */
  resume() {
    if (!this._canplay) {
      return;
    }
    if (this._pause_byother) {
      this.play();
    }
  }
  remove() {
    this._canplay = false;
    this._pause_byother = false;
    if (this._sound) {
      this._sound.stop();
      this._sound.unload();
    }
  }
  /**
   * 禁用
   */
  disabel() {
    this._disable = true;
  }
  /**
   * 启用
   */
  enable() {
    this._disable = false;
  }

  /**
   * 是否正在播放
   */
  get isPlaying() {
    if (!this._canplay) {
      return false;
    }

    return this._sound.playing();
  }
}

/**
 * 背景音乐播放器
 */
export const backgroundMusicPlayer = new SoundPlayer({ html5: false, loop: true });
/**
 * 自动导览录音播放器
 */
export const guideSoundPlayer = new SoundPlayer({ html5: false });
/**
 * 热点音频播放器
 */
export const hotspotSoundPlayer = new SoundPlayer({ html5: true, loop: true });
