import { r as registerInstance, h, c as getAssetPath, e as getElement } from './index-c04b9ed5.js';
import { g as get } from './localstorage.service-4bf408c8.js';
import { S as SparkleGlobal } from './util-57cc8006.js';

//https://github.com/bazh/subtitles-parser/blob/master/index.js
class CaptionParser {
  constructor() {
    this.pItems = {};
  }
  fromSrt(data, s) {
    var useSec = s ? true : false;
    data = data.replace(/\r/g, '');
    var regex = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/g;
    data = data.split(regex);
    data.shift();
    var items = {};
    // for (var i = 0; i < data.length; i += 4) {
    //     items.push({
    //         id: data[i].trim(),
    //         startTime: useMs ? this.timeMs(data[i + 1].trim()) : data[i + 1].trim(),
    //         endTime: useMs ? this.timeMs(data[i + 2].trim()) : data[i + 2].trim(),
    //         text: data[i + 3].trim()
    //     });
    // }
    for (var i = 0; i < data.length; i += 4) {
      items[useSec ? this.timeS(data[i + 1].trim()) : data[i + 1].trim()] = data[i + 3].trim();
    }
    return items;
  }
  ;
  toSrt(data) {
    if (!(data instanceof Array))
      return '';
    var res = '';
    for (var i = 0; i < data.length; i++) {
      var s = data[i];
      if (!isNaN(s.startTime) && !isNaN(s.endTime)) {
        s.startTime = this.msTime(parseInt(s.startTime, 10));
        s.endTime = this.msTime(parseInt(s.endTime, 10));
      }
      res += s.id + '\r\n';
      res += s.startTime + ' --> ' + s.endTime + '\r\n';
      res += s.text.replace('\n', '\r\n') + '\r\n\r\n';
    }
    return res;
  }
  ;
  // private timeMs(val) {
  //     var regex = /(\d+):(\d{2}):(\d{2}),(\d{3})/;
  //     var parts = regex.exec(val);
  //     if (parts === null) {
  //         return 0;
  //     }
  //     for (var i = 1; i < 5; i++) {
  //         // parts[i] = parseInt(parts[i], 10);
  //         // if (isNaN(parts[i])) parts[i] = 0;
  //         parts[i] = parseInt(parts[i], 10).toString();
  //         if (isNaN(parseInt(parts[i], 10))) parts[i] = "0";
  //     }
  //     // hours + minutes + seconds + ms
  //     return (parseInt(parts[1], 10) * 3600000) + (parseInt(parts[2], 10) * 60000) + (parseInt(parts[3], 10) * 1000) + parseInt(parts[4], 10);
  // };
  timeS(val) {
    var regex = /(\d+):(\d{2}):(\d{2}),(\d{3})/;
    var parts = regex.exec(val);
    if (parts === null) {
      return 0;
    }
    for (var i = 1; i < 5; i++) {
      // parts[i] = parseInt(parts[i], 10);
      // if (isNaN(parts[i])) parts[i] = 0;
      parts[i] = parseInt(parts[i], 10).toString();
      if (isNaN(parseInt(parts[i], 10)))
        parts[i] = "0";
    }
    // hours + minutes + seconds + ms
    return (parseInt(parts[1], 10) * 3600) + (parseInt(parts[2], 10) * 60) + (parseInt(parts[3], 10)) + Math.floor(parseInt(parts[4], 10) / 1000);
  }
  ;
  msTime(val) {
    var measures = [3600000, 60000, 1000];
    var time = [];
    for (var i in measures) {
      var res = (val / measures[i] >> 0).toString();
      if (res.length < 2)
        res = '0' + res;
      val %= measures[i];
      time.push(res);
    }
    var ms = val.toString();
    if (ms.length < 3) {
      for (let i = 0; i <= 3 - ms.length; i++)
        ms = '0' + ms;
    }
    return time.join(':') + ',' + ms;
  }
  ;
}

const sparkleAnimationPlayerCss = ".video-canvas{position:absolute;display:block;background-color:#f5f5f5;width:auto}.closed-caption{justify-content:flex-end;width:100%;display:flex}sparkle-animation-player{width:100%;margin:0 auto}.caption{position:absolute;bottom:0px;color:white;text-align:center;width:100%;text-shadow:1px 1px 2px #e50539}.canvas-container{width:680px;height:680px;background-color:#f5f5f5;border-radius:10px;position:relative}.frame-img{position:absolute;display:block;max-width:100%;width:100%;height:auto}.overlay-img{position:absolute;z-index:9999;top:0px;display:block;max-width:100%;width:100%;height:auto}.button-panel{display:flex;justify-content:center}ion-icon{color:var(--ion-color-primary)}.navControls{width:680px;background:transparent;border-radius:10px;position:relative;padding-top:15px;display:flex;flex-direction:column;align-items:center}.navControls .progressBar{flex:100%;border-radius:20px;position:relative;left:0;right:0;height:4px;background-color:rgba(205, 205, 205, 0.7);width:100%}.navControls .progressBar .currentProgress{border-radius:20px;position:absolute;height:25px;background-color:var(--ion-color-primary);transition:width 0.5s;width:100%}.navControls .progressBar .currentProgress:before{position:absolute;top:50%;right:4px;content:\" \";display:block;width:12px;height:12px;margin-top:-10px;background:#e5053a;border-radius:10px;border:4px solid #d9d4d4;z-index:10}#dom_overlay_container{pointer-events:none;overflow:hidden;position:absolute;left:0px;top:0px;display:block}.cavase-main-container{width:100%;display:flex;flex-wrap:wrap;justify-content:center;padding:15px;background-position:center;background-size:cover;background-repeat:no-repeat}.loading-container{height:100%;display:flex;justify-content:center;align-items:center}.uil-ring-css{position:absolute}ion-button{--ion-color-base:transparent;--ion-color-contrast:var(--ion-color-primary);--box-shadow:none !important}@media screen and (min-width: 760px){.navControls{flex-direction:row}.navControls .progressBar{height:24px;flex:75%;width:75%}.button-panel{flex:25%;width:25%}}";

const SparkleAnimationPlayer = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.showCaption = false;
    this.paused = true;
    this.dataLoaded = false;
    this.currentProgressWidth = 0;
    this.captionText = '';
    this.showFirstFrame = false;
    this.firstFramePath = '';
    this.isBusy = false;
    this.animationVideoProgress = '0';
    this.captionData = {};
  }
  closedCaptionChange(event) {
    this.showCaption = !this.showCaption;
  }
  onClassRoomModeChanged(event) {
    this.classMode = event.detail;
  }
  componentWillLoad() {
    // if (!this.isScriptLoaded(this.src)) {
    this.classMode = get(SparkleGlobal.LOCALSTORAGE_CLASSROOM_MODE);
    //this.classMode = this.initialClassMode;
    const script = document.createElement('script');
    this.firstFramePath = this.src.replace('.js', '.png');
    script.src = this.src;
    //script.async = true;
    document.body.appendChild(script);
    this.readTextFile(this.src.replace('.js', '.srt'));
    this.rergisterSoundControls();
    // }
    // else {
    //   console.log("script loaded", this.src);
    // }
  }
  readTextFile(fileName) {
    let that = this;
    var rawFile = new XMLHttpRequest();
    rawFile.open('GET', fileName, false);
    rawFile.onreadystatechange = function () {
      if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
          var allText = rawFile.responseText;
          var parser = new CaptionParser();
          that.captionData = parser.fromSrt(allText, true);
        }
      }
    };
    rawFile.send(null);
  }
  isScriptLoaded(url) {
    var scripts = document.getElementsByTagName('script');
    for (var i = scripts.length; i--;) {
      if (scripts[i].getAttribute('src') == url) {
        return true;
      }
    }
    return false;
  }
  rergisterSoundControls() {
    window['playSound'] = (id, loop) => {
      if (this.sound) {
        this.sound.stop();
      }
      this.sound = createjs.Sound.play(id, { interrupt: createjs.Sound.INTERRUPT_EARLY, loop: 0, volume: 1 });
      return this.sound;
    };
    window['resetToStart'] = () => {
      console.log('reset');
      this.rewindAnimationToStart();
    };
  }
  startLoading() {
    this.isBusy = true;
    this.paused = false;
  }
  doneLoading() {
    this.isBusy = false;
    this.dataLoaded = true;
    this.paused = false;
  }
  handleFileLoad(evt) {
    var images = this.comp.getImages();
    if (evt && evt.item.type == 'image') {
      images[evt.item.id] = evt.result;
    }
  }
  handleQueueProgress(that) {
    return progress => {
      this.animationVideoProgress = progress.loaded ? (progress.loaded * 100).toFixed(0) : '0';
      if (progress.loaded == 1) {
        this.doneLoading();
      }
    };
  }
  handleComplete(evt) {
    var ss = this.comp.getSpriteSheet();
    var queue = evt.target;
    //var lib = this.comp.getLibrary();
    var ssMetadata = this.library.ssMetadata;
    for (var i = 0; i < ssMetadata.length; i++) {
      ss[ssMetadata[i].name] = new createjs.SpriteSheet({ images: [queue.getResult(ssMetadata[i].name)], frames: ssMetadata[i].frames });
    }
    var jsFileName = this.src.substring(this.src.lastIndexOf('/') + 1, this.src.lastIndexOf('.'));
    this.exportRoot = new this.library[jsFileName]();
    this.stage = new this.library.Stage(this.canvas);
    this.makeResponsive(true, 'both', false, 1);
    AdobeAn.compositionLoaded(this.library.properties.id);
    this.stage.addChild(this.exportRoot);
    createjs.Ticker.framerate = this.library.properties.fps;
    createjs.Ticker.paused = false;
    createjs.Ticker.addEventListener('tick', this.stage);
    createjs.Ticker.addEventListener('tick', evt => {
      this.tickHandler(evt);
    });
    // this.rewindAnimationToStart();
    // this.playPauseAnimation();
  }
  loadAnimation() {
    this.startLoading();
    if (!createjs.Sound.initializeDefaultPlugins()) {
      return;
    }
    this.canvas = this.el.querySelector('.video-canvas');
    this.anim_container = this.el.querySelector('.canvas-container');
    this.comp = AdobeAn.getComposition(this.composition);
    this.canvas.style.width = '100%';
    this.canvas.style.height = this.canvas.offsetWidth + 'px';
    this.anim_container.style.height = this.canvas.offsetWidth + 'px';
    this.library = this.comp.getLibrary();
    this.loader = new createjs.LoadQueue(false);
    this.loader.setMaxConnections(3);
    this.loader.maintainScriptOrder = true;
    this.loader.installPlugin(createjs.Sound);
    this.loader.addEventListener('complete', evt => {
      this.handleComplete(evt);
    });
    this.loader.addEventListener('fileload', evt => {
      this.handleFileLoad(evt);
    });
    this.loader.addEventListener('progress', this.handleQueueProgress(this));
    //TODO :can't figure out https://github.com/CreateJS/SoundJS/issues/283
    this.loader.loadManifest(this.library.properties.manifest, true, this.src.substring(0, this.src.lastIndexOf('/') + 1));
  }
  playButtonAction() {
    if (!this.dataLoaded) {
      this.loadAnimation();
    }
    else {
      this.playPauseAnimation();
    }
  }
  playPauseAnimation() {
    let newState = !createjs.Ticker.paused;
    if (newState) {
      this.pauseAnimation();
    }
    else {
      this.playAnimation();
    }
  }
  async playAnimation() {
    this.showFirstFrame = false;
    if (this.loader != null) {
      this.loader.close();
    }
    if (createjs && createjs.Ticker) {
      let newState = false;
      let st = this.sound;
      if (st) {
        st.paused = newState;
      }
      createjs.Ticker.paused = newState;
      createjs.Ticker.addEventListener('tick', this.stage);
      this.paused = newState;
      // let stage = this.stage.children[0];
      // stage.gotoAndStop(0);
      // this.stage.update();
    }
  }
  async pauseAnimation() {
    if (this.loader != null) {
      this.loader.close();
    }
    if (createjs && createjs.Ticker) {
      let newState = true;
      let st = this.sound;
      if (st) {
        st.paused = newState;
      }
      createjs.Ticker.paused = newState;
      createjs.Ticker.removeEventListener('tick', this.stage);
      this.paused = newState;
    }
  }
  disconnectedCallback() {
    this.pauseAnimation();
    createjs.Sound.removeAllSounds();
    // if (this.stage && this.stage.children) {
    //   let stage = this.stage.children[0];
    //   let timeline = stage["timeline"];
    //   this.stage.clear();
    //   stage.removeAllChildren()
    //   stage.removeAllEventListeners()
    //   stage.canvas = null
    //   stage._eventListeners = null;
    // }
  }
  async classRoomModeChanged(val) {
    this.classMode = val;
  }
  async destroyAnimation() {
    this.pauseAnimation();
    // if (this.stage && this.stage.children) {
    //   let stage = this.stage.children[0];
    //   let timeline = stage["timeline"];
    //   this.stage.clear();
    //   stage.removeAllChildren();
    //   stage.removeAllEventListeners();
    //   stage.canvas = null
    //   stage._eventListeners = null;
    // }
  }
  makeResponsive(isResp, respDim, isScale, scaleType) {
    window.addEventListener('resize', () => this.resizeCanvas(isResp, respDim, isScale, scaleType));
    this.resizeCanvas(isResp, respDim, isScale, scaleType);
  }
  resizeCanvas(isResp, respDim, isScale, scaleType) {
    //var lib = this.comp.getLibrary();
    var lastW, lastH, lastS = 1;
    var w = this.library.properties.width, h = this.library.properties.height;
    var iw = window.innerWidth, ih = window.innerHeight;
    var pRatio = window.devicePixelRatio || 1, xRatio = iw / w, yRatio = ih / h, sRatio = 1;
    if (isResp) {
      if ((respDim == 'width' && lastW == iw) || (respDim == 'height' && lastH == ih)) {
        sRatio = lastS;
      }
      else if (!isScale) {
        if (iw < w || ih < h) {
          sRatio = Math.min(xRatio, yRatio);
        }
      }
      else if (scaleType == 1) {
        sRatio = Math.min(xRatio, yRatio);
      }
      else if (scaleType == 2) {
        sRatio = Math.max(xRatio, yRatio);
      }
    }
    var anim_container = this.el.querySelector('.canvas-container');
    // this.canvas.width = w * pRatio * sRatio;
    // this.canvas.height = h * pRatio * sRatio;
    // this.canvas.style.width = this.dom_overlay_container.style.width = anim_container.style.width = w * sRatio + 'px';
    // this.canvas.style.height = anim_container.style.height = this.dom_overlay_container.style.height = h * sRatio + 'px';
    this.canvas.width = w * pRatio * sRatio;
    this.canvas.height = h * pRatio * sRatio;
    this.canvas.style.width = '100%';
    this.canvas.style.height = this.canvas.offsetWidth + 'px';
    anim_container.style.height = this.canvas.offsetWidth + 'px';
    this.stage.scaleX = pRatio * sRatio;
    this.stage.scaleY = pRatio * sRatio;
    lastW = iw;
    lastH = ih;
    lastS = sRatio;
    var newWidth = this.canvas.offsetWidth;
    this.sizeOfCanvas = newWidth;
    var progressBar = this.el.querySelector('.progressBar');
    this.sizeofProgressBar = progressBar.offsetWidth;
    this.stage.tickOnUpdate = false;
    this.stage.update();
    this.stage.tickOnUpdate = true;
  }
  tickHandler(event) {
    if (!event.paused) {
      let stage = this.stage.children[0];
      this.timeline = stage['timeline'];
      if (this.captionData[Math.floor(this.timeline.position / this.library.properties.fps)]) {
        this.captionText = this.captionData[Math.floor(this.timeline.position / this.library.properties.fps)];
      }
      if (this.timeline.position % 10 == 0) {
        console.log(this.timeline.duration - 10, this.timeline.position);
        if (this.timeline.position > (this.timeline.duration - 10)) {
          this.animationCompleted();
        }
        this.currentProgressWidth = parseFloat(((this.timeline.position / this.timeline.duration) * this.sizeofProgressBar).toFixed(0));
      }
    }
  }
  animationCompleted() {
    console.log('completed');
    this.showFirstFrame = true;
    this.rewindAnimationTo(0);
    this.pauseAnimation();
  }
  rewindAnimationTo(newPosition) {
    let st = this.sound;
    if (st) {
      st.paused = true;
    }
    let stage = this.stage.children[0];
    let timeline = stage['timeline'];
    if (newPosition < 0) {
      newPosition = 0;
    }
    if (newPosition > timeline.duration) {
      newPosition = timeline.duration - 10;
    }
    //this.sound.setPosition(soundPosition);
    //this.sound.position = soundPosition;
    if (this.paused) {
      stage.gotoAndStop(newPosition);
      this.stage.update();
      if (st && !st.getPaused()) {
        //st.paused = true;
        createjs.Ticker.paused = true;
      }
    }
    else {
      stage.gotoAndPlay(newPosition);
      //st.paused = false;
      createjs.Ticker.paused = false;
    }
  }
  rewindAnimationToStart() {
    this.paused = true;
    let newPosition = 0;
    // var soundPosition = this.sound.position + 5000;
    // console.log("video", newPosition / 1000);
    // console.log("sound", soundPosition / 1000);
    this.rewindAnimationTo(newPosition);
    // if (this.loader != null) {
    //   this.loader.close();
    // }
    // let stage = this.stage.children[0];
    // console.log(stage);
    // stage.stop();
    // stage["timeline"].setPosition(0);
    // stage["timeline"].updateDuration(0);
    // this.stage.update();
    // if (createjs && createjs.Ticker) {
    //   let newState = true;
    //   let st = this.sound;
    //   if (st) {
    //     st.paused = newState;
    //   }
    //   createjs.Ticker.paused = newState;
    //   createjs.Ticker.removeEventListener("tick", this.stage);
    //   this.paused = newState;
    // }
  }
  rewindAnimation(event) {
    event.stopPropagation();
    let stage = this.stage.children[0];
    let timeline = stage['timeline'];
    let newPosition = Math.round((event.offsetX / this.sizeofProgressBar) * timeline.duration);
    // var soundPosition = this.sound.position + 5000;
    // console.log("video", newPosition / 1000);
    // console.log("sound", soundPosition / 1000);
    this.rewindAnimationTo(newPosition);
  }
  rewind5Sec() {
    let fps = this.library.properties.fps;
    let stage = this.stage.children[0];
    let timeline = stage['timeline'];
    let newPosition = timeline.position - fps * 5;
    //var soundPosition = this.sound.position - 5000;
    this.rewindAnimationTo(newPosition);
  }
  fastForward5Sec() {
    let fps = this.library.properties.fps;
    let stage = this.stage.children[0];
    let timeline = stage['timeline'];
    let newPosition = timeline.position + fps * 5;
    // var soundPosition = this.sound.position + 5000;
    this.rewindAnimationTo(newPosition);
  }
  muteVolume() {
    let st = this.sound;
    if (st) {
      st.volume = 0;
    }
  }
  downVolume() {
    let st = this.sound;
    if (st) {
      if (st._getVolume() > 0.9) {
        st.volume = st._getVolume() - 0.1;
      }
    }
  }
  upVolume() {
    let st = this.sound;
    if (st) {
      if (st._getVolume() < 1) {
        st.volume = st._getVolume() + 0.1;
      }
    }
  }
  render() {
    return (h("div", { class: "cavase-main-container" }, h("div", { class: "canvas-container", id: "canvas-container" }, !this.classMode ? (h("div", null, h("canvas", { class: "video-canvas", onClick: () => this.playButtonAction() }), this.showCaption ? h("div", { class: "caption" }, this.captionText) : '')) : (''), !this.dataLoaded || this.showFirstFrame ? h("img", { class: "frame-img", src: this.firstFramePath }) : '', this.classMode ? h("img", { class: "overlay-img", src: getAssetPath(`./assets/play-button-disabled-overlay.png`) }) : '', !this.classMode && this.paused ? h("img", { class: "overlay-img", onClick: () => this.playButtonAction(), src: getAssetPath(`./assets/play-button-overlay.png`) }) : '', this.isBusy ? (h("div", { class: "loading-container" }, h("div", { class: "uil-ring-css" }, h("div", null), h("a", null, "Loading ", this.animationVideoProgress, "%")))) : ('')), this.dataLoaded ? (h("div", { class: "navControls" }, h("div", { class: "progressBar", onClick: ev => this.rewindAnimation(ev) }, h("div", { class: "currentProgress", style: { width: this.currentProgressWidth + 'px' } })), h("div", { class: "button-panel" }, h("ion-button", { size: "small", color: "transperant", onClick: () => this.rewind5Sec() }, ' ', h("ion-icon", { name: "play-back-outline" }), ' '), h("ion-button", { size: "small", color: "transperant", onClick: () => this.playButtonAction() }, ' ', this.paused ? (h("ion-icon", { name: "pause-outline" })) : (h("ion-icon", { name: "play-outline" })
    // <ion-icon src="/assets/img/play-symbol.svg"></ion-icon>
    )), h("ion-button", { size: "small", color: "transperant", onClick: () => this.fastForward5Sec() }, ' ', h("ion-icon", { name: "play-forward-outline" }))))) : (''), this.dataLoaded && this.captionText ? (h("div", { class: "closed-caption" }, h("ion-item", { lines: "none" }, h("ion-label", null, "Closed Caption"), h("ion-toggle", { slot: "end", color: "primary", checked: this.showCaption })))) : ('')));
  }
  static get assetsDirs() { return ["assets"]; }
  get el() { return getElement(this); }
};
SparkleAnimationPlayer.style = sparkleAnimationPlayerCss;

export { SparkleAnimationPlayer as sparkle_animation_player };
