var story_component_audio_player_internal = [];

function story_component_audio_load() {
  for (key in dataStory) {
    var dataObject = dataStory[key];

    if (dataObject["objectType"] == "audio") {
      //grp
      var object = new Konva.Group({
        id: key,
        x: dataObject["x"],
        y: dataObject["y"],
      });
      grpStory.add(object);
      object.setAttr("data", dataObject);

      //rect
      var rect = new Konva.Rect({
        x: 0,
        y: 0,
        width: dataObject["width"],
        height: dataObject["height"],
      });
      object.add(rect);

      //audio
      if (dataObject["image"]) {
        story_component_audio_player_internal[key] = new Audio();
        story_component_audio_player_internal[key].src =
          stagePath + dataObject["image"];

        if (dataObject["autoPlay"] == "1") {
          autoPlayAudio = story_component_audio_player_internal[key];
        }
      }

      object.on("pointerdown ", function () {
        story_component_audio_click(this);
      });

      initButton(object, 0);
    }
  }
}

function story_component_audio_click(e) {
  var action = e.getAttr("data")["action"];
  if (!action) {
    action = "play";
  }

  story_component_audio_pauseall();

  switch (action) {
    case "play":
      story_component_audio_player_internal[e.id()].play();
      break;

    case "pause":
      story_component_audio_player_internal[
        e.getAttr("data")["target"]
      ].pause();
      break;

    case "start":
      story_component_audio_player_internal[
        e.getAttr("data")["target"]
      ].currentTime = 0;
      story_component_audio_player_internal[e.getAttr("data")["target"]].play();
      break;
  }
}

function story_component_audio_pauseall() {
  for (key in dataStory) {
    let dataObject = dataStory[key];
    if (dataObject["objectType"] == "audio") {
      if (dataObject["image"]) {
        story_component_audio_player_internal[key].pause();
      }
    }
  }
}

function story_component_audio_autoplay() {
  story_component_audio_pauseall();
  for (key in dataStory) {
    let dataObject = dataStory[key];
    if (
      dataObject["objectType"] == "audio" &&
      dataObject["image"] &&
      dataObject["autoPlay"] == "1"
    ) {
      let ys = (pageCur - 1) * defaultStageHeight;
      let ye = pageCur * defaultStageHeight;
      if (dataObject["y"] > ys && dataObject["y"] < ye) {
        //story_component_audio_player_internal[key].play();
        autoPlayAudio = story_component_audio_player_internal[key];
        autoPlayAudio.currentTime = 0;
        autoPlayAudio.play();
      }
    }
  }
}
