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

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

      //target
      var answerText = new Konva.Text({
        id: "target",
        x: parseInt(dataObject["targetX"]),
        y: parseInt(dataObject["targetY"]),
        fill: dataObject["targetFill"],
        fontSize: parseInt(dataObject["targetFontSize"]),
        //width: width,
        //align: align,
        fontStyle: "bold",
        fontFamily: "Trebuchet MS, sans-serif",
        lineHeight: 1.5,
        letterSpacing: 10,
        textDecoration: "underline",
        data: dataObject,
      });
      object.add(answerText);

      //grpLetters
      var grpLetters = new Konva.Group({
        id: "grpLetters",
        x: 0,
        y: 0,
      });
      object.add(grpLetters);
      answer = dataObject["target"];

      /*

        split taget

      */
      let nextX = 0;

      if (dataObject["autoSplit"]) {
        //otomatik split
        //her harfi tek kutu yapar

        //harfleri karıştır
        let letters = answer.split("");

        letters = story_component_wordbox_shuffleArray(letters);

        //harfleri oluştur
        for (let i = 0; i < letters.length; i++) {
          let letter = letters[i];

          let grpLetter = story_component_wordbox_create_box(
            letter,
            nextX,
            null,
            dataObject,
            true
          );
          grpLetters.add(grpLetter);

          nextX +=
            parseInt(dataObject["imageWidth"]) +
            parseInt(dataObject["boxSpace"]);
        }
      } else {
        //autosplit off
        // target i --- lere böl ve kutu olustur
        let parts = answer.split("---");
        parts = story_component_wordbox_shuffleArray(parts);
        parts.forEach((element) => {
          let width = element.length * (parseInt(dataObject["imageWidth"]) / 2);

          let grpLetter = story_component_wordbox_create_box(
            element,
            nextX,
            width,
            dataObject,
            false
          );
          grpLetters.add(grpLetter);

          nextX += width + 10;
        });
      }

      //grpLetters.x(((defaultStageWidth-dataObject['x'])-nextX)/2);

      //resetButton
      let resetButtonImageSrc = new Image();
      let resetButtonImage = new Konva.Image({
        id: "resetButton",
        image: resetButtonImageSrc,
        target: key,
        x: -16,
        y: -16,
      });
      object.add(resetButtonImage);
      resetButtonImageSrc.src = stagePath + "letterbox_reset.svg";
      initButton(resetButtonImage, 0);
      resetButtonImage.on("pointerdown ", function (e) {
        story_component_wordbox_resetSelf(e);
      });
    }
  }
}

function story_component_wordbox_resetSelf(e) {
  let key = e.currentTarget.getAttr("target");
  let obj = grpStory.findOne("#" + key);

  let grpLetters = obj.findOne("#grpLetters");
  let target = obj.findOne("#target");
  target.text("");

  var letters = grpLetters.getChildren();

  for (key in letters) {
    letters[key].show();

    var tween = new Konva.Tween({
      node: letters[key],
      duration: Math.random(letters.length),
      opacity: 1,
      easing: Konva.Easings.StrongEaseInOut,
    });
    tween.play();
  }
}

function story_component_wordbox_shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

function story_component_wordbox_create_box(
  letter,
  nextX,
  width,
  dataObject,
  isBoxImage = true
) {
  //grpLetter
  let grpLetter = new Konva.Group({
    x: nextX,
    letter: letter,
  });
  initButton(grpLetter, 0);

  grpLetter.on("pointerdown ", function () {
    story_check_unlock = true;

    _object = this.getParent().getParent();
    _target = _object.findOne("#target");

    let letter = this.getAttr("letter");
    this.hide();
    this.opacity(0);
    answerWord = _target.text() + letter;
    _target.text(answerWord);
  });

  let fontSize = parseInt(dataObject["imageWidth"]) / 2;
  if (!width) {
    width = parseInt(dataObject["imageWidth"]);
  }

  //letterBoxImage
  if (isBoxImage) {
    var letterBoxImageSrc = new Image();
    var letterBoxImage = new Konva.Image({
      image: letterBoxImageSrc,
    });
    grpLetter.add(letterBoxImage);
    letterBoxImageSrc.src = stagePath + dataObject["image"];
  } else {
    //rect

    let rect = new Konva.Rect({
      id: "rect",
      x: 0,
      y: 0,
      width: width,
      height: dataObject["imageHeight"],
      opacity: 1,
      stroke: dataObject["boxFill"],
      strokeWidth: 2,
    });
    grpLetter.add(rect);
  }

  //letterBoxText
  var letterBoxText = new Konva.Text({
    y: (parseInt(dataObject["imageHeight"]) - (fontSize + 7)) / 2,
    width: width,
    fontSize: fontSize,
    fill: dataObject["boxFill"],
    text: letter,
    align: "center",
    fontStyle: "bold",
    fontFamily: "Trebuchet MS, sans-serif",
    lineHeight: 1.5,
  });
  grpLetter.add(letterBoxText);

  return grpLetter;
}

function story_component_wordbox_checker(obj, trueFalse) {
  var imageSrc = new Image();
  imageSrc.onload = function () {
    var checker = new Konva.Image({
      id: "checker",
      x: parseInt(obj.getAttr("data")["checkerX"]),
      y: parseInt(obj.getAttr("data")["checkerY"]),
      width: parseInt(obj.getAttr("data")["checkerWidth"]),
      height: parseInt(obj.getAttr("data")["checkerHeight"]),
      image: imageSrc,
    });
    obj.add(checker);
  };

  if (trueFalse) {
    imageSrc.src = stagePath + obj.getAttr("data")["checkerCorrect"];
  } else {
    imageSrc.src = stagePath + obj.getAttr("data")["checkerWrong"];
  }
}
function story_component_wordbox_check() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (obj.getAttr("data") && obj.getAttr("data")["objectType"] == "wordbox") {
      storyTotalObject++;
      let target = obj.findOne("#target");

      let targetText = obj.getAttr("data")["target"].split("---").join("");

      resetButton = obj.findOne("#resetButton");
      resetButton.hide();

      if (target.text() == targetText) {
        storyTotalCorrect++;
        obj.setAttr("success", true);
        story_component_wordbox_checker(obj, true);
      } else {
        story_component_wordbox_checker(obj, false);
      }

      //hide letterboxes
      grpLetters = obj.findOne("#grpLetters");
      var letters = grpLetters.getChildren();
      for (key in letters) {
        letters[key].hide();
      }
    }
  }
}

function story_component_wordbox_solve() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (obj.getAttr("data") && obj.getAttr("data")["objectType"] == "wordbox") {
      grpLetters = obj.findOne("#grpLetters");
      target = obj.findOne("#target");
      resetButton = obj.findOne("#resetButton");
      resetButton.hide();

      let targetText = obj.getAttr("data")["target"].split("---").join("");
      target.text(targetText);

      checker = obj.findOne("#checker");
      if (checker) {
        checker.destroy();
      }

      var letters = grpLetters.getChildren();
      for (key in letters) {
        letters[key].hide();
      }
    }
  }
}

function story_component_wordbox_reset() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (obj.getAttr("data") && obj.getAttr("data")["objectType"] == "wordbox") {
      grpLetters = obj.findOne("#grpLetters");
      target = obj.findOne("#target");
      target.text("");

      resetButton = obj.findOne("#resetButton");
      resetButton.show();

      checker = obj.findOne("#checker");
      if (checker) {
        checker.destroy();
      }

      var letters = grpLetters.getChildren();

      for (key in letters) {
        letters[key].show();

        var tween = new Konva.Tween({
          node: letters[key],
          duration: Math.random(letters.length),
          opacity: 1,
          easing: Konva.Easings.StrongEaseInOut,
        });
        tween.play();
      }
    }
  }
}
