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

    switch (dataObject["objectType"]) {
      case "dragTarget":
        var object = new Konva.Rect({
          id: key,
          x: parseInt(dataObject["x"]),
          y: parseInt(dataObject["y"]),
          width: parseInt(dataObject["width"]),
          height: parseInt(dataObject["height"]),
          data: dataObject,
        });
        grpStory.add(object);
        break;

      case "dragSource":
        var object = new Konva.Group({
          id: key,
          x: parseInt(dataObject["x"]),
          y: parseInt(dataObject["y"]),
          xs: parseInt(dataObject["x"]),
          ys: parseInt(dataObject["y"]),
          draggable: true,
          qcObject: true,
          targetted: "",
          data: dataObject,
        });
        grpStory.add(object);

        //image:qcimage
        /*
        if (dataObject["image"]) {
          var image = qcImage({
            src: dataObject["image"],
            image_type: dataObject["image_type"],
            x: parseInt(dataObject["imageX"]),
            y: parseInt(dataObject["imageY"]),
            width: parseInt(dataObject["imageWidth"]),
            height: parseInt(dataObject["imageHeight"]),
            frameRate: parseInt(dataObject["frameRate"]),
            sprite_sheet: dataObject["sprite_sheet"],
          });
          object.add(image);
        }
        */

        //image:konva
        if (dataObject["image"]) {
          var image;
          var imageSrc = new Image();
          imageSrc.onload = function () {};
          image = new Konva.Image({
            x: parseInt(dataObject["imageX"]),
            y: parseInt(dataObject["imageY"]),
            width: parseInt(dataObject["imageWidth"]),
            height: parseInt(dataObject["imageHeight"]),
            image: imageSrc,
          });
          imageSrc.src = stagePath + dataObject["image"];
          object.add(image);
        }

        //text
        if (dataObject["text"]) {
          var text = new Konva.Text({
            x: parseInt(dataObject["textX"]),
            y: parseInt(dataObject["textY"]),
            width: parseInt(dataObject["textWidth"]),
            fontSize: parseInt(dataObject["textSize"]),
            fill: dataObject["textColor"],
            text: dataObject["text"],
            fontStyle: "bold",
            fontFamily: "Trebuchet MS, sans-serif",
            lineHeight: 1.1,
            stroke: dataObject["textStrokeColor"],
            strokeWidth: dataObject["textStrokeWidth"],
            fillAfterStrokeEnabled: true,
            lineJoin: "round",
            lineCap: "round",
            align: "center",
          });
          object.add(text);
        }

        object.on("dragstart ", function () {
          dragStart(this);
        });
        object.on("dragend ", function () {
          dragEnd(this);
        });

        initButton(object, 0);
        break;
    }
  }
}
function dragStart(e) {
  e.moveToTop();
}
function dragEnd(e) {
  var pos = grpStory.getRelativePointerPosition();

  //source obje target objenin içinde ise...
  //artik kullanilmiyor
  //bunun yerine mouse x,y ye bakiyoruz aşağıda
  //var x = e.x() +( e.width() / 2);
  //var y = e.y() + ( e.height() / 2);

  var x = pos.x;
  var y = pos.y;

  var id = e.getAttr("data")["target"];
  var target = null;

  var objects = grpStory.getChildren();

  //dragTarget lere bakiyoruz, dragSource objemiz hangisinin içine sürüklenmiş?
  for (key in objects) {
    var obj = objects[key];
    if (
      obj.getAttr("data") &&
      obj.getAttr("data")["objectType"] == "dragTarget"
    ) {
      var x1 = obj.x();
      var x2 = obj.x() + obj.width();
      var y1 = obj.y();
      var y2 = obj.y() + obj.height();
      if (x > x1 && x < x2 && y > y1 && y < y2) {
        target = obj;
      }
    }
  }

  if (target) {
    story_check_unlock = true;

    if (target.getAttr("data")["group"] == e.getAttr("data")["group"]) {
      e.setAttr("targetted", target.id());

      //maxSource ayari girilmis ise
      //tüm dragSource objeleri tariyoruz
      //bu hedefe onceden suruklenmis varmi bakiyoruz
      var maxSource = target.getAttr("data")["maxSource"];
      var curSourceCount = 0;
      if (maxSource) {
        for (key in objects) {
          var obj2 = objects[key];
          if (
            obj2.getAttr("data") &&
            obj2.getAttr("data")["objectType"] == "dragSource"
          ) {
            var x = obj2.x();
            var y = obj2.y();
            var x1 = target.x();
            var x2 = target.x() + target.width();
            var y1 = target.y();
            var y2 = target.y() + target.height();
            //if( x > x1-1 && x < x2+1 && y > y1-1 && y < y2+1){ //eski hesaplama x,y ye göre
            if (obj2.getAttr("targetted") == target.id()) {
              //yeni hesaplama targetted degerine göre

              //obje daha onceden bu hedefe suruklenmis
              //eger bu obje simdiki obje degilse
              if (obj2 != e) {
                //hedefteki obje sayisini artiyoruz
                curSourceCount++;
                //limite ulasirsa fazla gelen objeyi (son konan) geri gonderiyoruz
                if (curSourceCount >= maxSource) {
                  dragPositonReset(obj2);
                }
              }
            }
          }
        }
      }

      targetX = parseInt(e.getAttr("data")["targetX"]);
      targetY = parseInt(e.getAttr("data")["targetY"]);

      if (targetX != null) {
        x = target.x() + targetX;
      } else {
        var x = target.x() + (target.width() - e.width()) / 2;
      }
      if (targetY != null) {
        y = target.y() + targetY;
      } else {
        var y = target.y() + (target.height() - e.height()) / 2;
      }

      var tween = new Konva.Tween({
        node: e,
        duration: 0.5,
        x: x,
        y: y,
        easing: Konva.Easings.ElasticEaseInOut,
        onFinish: function () {},
      });
      tween.play();
    } else {
      dragPositonReset(e);
    }
  } else {
    dragPositonReset(e);
  }
}
function dragPositonReset(e) {
  var xs = e.getAttr("xs");
  var ys = e.getAttr("ys");
  var tween = new Konva.Tween({
    node: e,
    duration: 1,
    x: xs,
    y: ys,
    easing: Konva.Easings.ElasticEaseInOut,
  });
  tween.play();
}

function dragChecker(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 dragCheck() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (
      obj.getAttr("qcObject") &&
      obj.getAttr("data")["objectType"] == "dragSource"
    ) {
      obj.listening(false);

      var x = obj.x() + obj.width() / 2;
      var y = obj.y() + obj.height() / 2;

      if (obj.getAttr("data")["target"]) {
        storyTotalObject++;
        if (Array.isArray(obj.getAttr("data")["target"])) {
          //coklu hedef
          //1) obj.getAttr('target')=kaynak objenin dogru targetler arrayi
          //2) obj.getAttr('targetted')=sürükle-birak kısmında hedefe birakildiginda targetted olarak hedef id sini kayit etmistik
          //1 in icinde 2 varmi diye bakiyorz, var ise dogru hedeflerden birindedir
          //parseInt yapiyoruz cunku pandelen array ["1","2","3"] olarak gelemiyor [1,2,3,4] olarak geliyor, arrayimizin icindekiler 1 2 3 targetted ise "1" "2" "3" gibi olunca eslemdigi icin parseInt yapiyoruz
          if (
            obj
              .getAttr("data")
              ["target"].includes(parseInt(obj.getAttr("targetted")))
          ) {
            storyTotalCorrect++;
            dragChecker(obj, true);
            obj.setAttr("success", true);
          } else {
            dragChecker(obj, false);
          }
        } else {
          //tek hedef
          if (obj.getAttr("data")["target"] == obj.getAttr("targetted")) {
            storyTotalCorrect++;
            dragChecker(obj, true);
            obj.setAttr("success", true);
          } else {
            dragChecker(obj, false);
          }
        }
      } else {
        if (obj.getAttr("targetted")) {
          //wrong
          dragChecker(obj, false);
        } else {
          //correct
          obj.setAttr("success", true);
        }
      }
    }
  }
}

function dragSolve() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];

    if (
      obj.getAttr("data") &&
      obj.getAttr("data")["objectType"] == "dragSource"
    ) {
      checker = obj.findOne("#checker");
      if (checker) {
        checker.destroy();
      }

      obj.listening(false);

      if (obj.getAttr("data")["target"]) {
        if (Array.isArray(obj.getAttr("data")["target"])) {
          //coklu hedef
          //arraydaki ilk objeyi hedef al
          var target = grpStory.findOne("#" + obj.getAttr("data")["target"][0]);
        } else {
          //tek hedef
          var target = grpStory.findOne("#" + obj.getAttr("data")["target"]);
        }

        var targetX = parseInt(obj.getAttr("data")["targetX"]);
        var targetY = parseInt(obj.getAttr("data")["targetY"]);

        if (targetX != null) {
          x = target.x() + targetX;
        } else {
          var x = target.x() + (target.width() - obj.width()) / 2;
        }
        if (targetY != null) {
          y = target.y() + targetY;
        } else {
          var y = target.y() + (target.height() - obj.height()) / 2;
        }
      } else {
        x = obj.getAttr("xs");
        y = obj.getAttr("ys");
      }

      var tween = new Konva.Tween({
        node: obj,
        duration: 1,
        x: x,
        y: y,
        easing: Konva.Easings.ElasticEaseInOut,
      });
      tween.play();
    }
  }
}

function dragReset() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (
      obj.getAttr("data") &&
      obj.getAttr("data")["objectType"] == "dragSource"
    ) {
      obj.x(obj.getAttr("xs"));
      obj.y(obj.getAttr("ys"));

      obj.setAttr("targetted", "");
      obj.setAttr("success", null);
      obj.listening(true);

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