var matchObjectBefore;
var matchObjectNow;
var matchObjectState = false;

//grpMatchLines
var grpMatchLines = new Konva.Group({
  x: 0,
  y: 0,
});
grpStory.add(grpMatchLines);

//matchLiner
var matchLiner = new Konva.Line({
  stroke: "#000",
  strokeWidth: 10,
  lineCap: "round",
  lineJoin: "round",
});
grpStory.add(matchLiner);

//matchLoad
function matchLoad() {
  for (key in dataStory) {
    var dataObject = dataStory[key];
    if (dataObject["objectType"] == "match") {
      //grp
      var object = new Konva.Group({
        id: key,
        x: parseInt(dataObject["x"]),
        y: parseInt(dataObject["y"]),
        targetted: "",
        data: dataObject,
      });
      grpStory.add(object);

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

      initButton(object, 0);

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

      object.check = function () {
        return matchCheck(this);
      };
      object.solve = function () {
        matchSolve(this);
      };
    }
  }
}

//matchClick
function matchClick(e) {
  //if (e.getAttr("targetted") == "" && matchObjectNow != e) {
  if (matchObjectNow != e) {
    //tıklanan obje daha önce hedeflenmemiş ise

    if (
      matchObjectState &&
      matchObjectNow.getAttr("data")["group"] != e.getAttr("data")["group"]
    ) {
      story_check_unlock = true;

      matchObjectBefore = matchObjectNow;
      matchObjectNow = e;
      matchObjectState = false;

      if (
        matchObjectNow.getAttr("data")["group"] !=
        matchObjectBefore.getAttr("data")["group"]
      ) {
        //önceki ve soraki objeleri hedeflettir
        matchObjectBefore.setAttr("targetted", matchObjectNow.id());
        matchObjectNow.setAttr("targetted", matchObjectBefore.id());

        var i = matchObjectBefore.getAttr("i");

        //object now x,y
        var matchObjectNowTargetX = parseInt(
          dataStory[matchObjectNow.id()]["targetX"]
        );
        var matchObjectNowTargetY = parseInt(
          dataStory[matchObjectNow.id()]["targetY"]
        );

        if (matchObjectNowTargetX != null) {
          var x2 = matchObjectNow.x() + matchObjectNowTargetX;
        } else {
          var x2 = matchObjectNow.x() + matchObjectNow.width() / 2;
        }
        if (matchObjectNowTargetY != null) {
          var y2 = matchObjectNow.y() + matchObjectNowTargetY;
        } else {
          var y2 = matchObjectNow.y() + matchObjectNow.height() / 2;
        }

        //object before x,y
        var matchObjectBeforeTargetX = parseInt(
          dataStory[matchObjectBefore.id()]["targetX"]
        );
        var matchObjectBeforeTargetY = parseInt(
          dataStory[matchObjectBefore.id()]["targetY"]
        );
        if (matchObjectBeforeTargetX != null) {
          var x1 = matchObjectBefore.x() + matchObjectBeforeTargetX;
        } else {
          var x1 = matchObjectBefore.x() + matchObjectBefore.width() / 2;
        }

        if (matchObjectBeforeTargetY != null) {
          var y1 = matchObjectBefore.y() + matchObjectBeforeTargetY;
        } else {
          var y1 = matchObjectBefore.y() + matchObjectBefore.height() / 2;
        }

        x1 = Math.round(x1);
        y1 = Math.round(y1);
        x2 = Math.round(x2);
        y2 = Math.round(y2);

        //eşleştirme çizginisi çiz
        var lineColor = dataStory[matchObjectBefore.id()]["lineColor"];
        var lineStroke = parseInt(
          dataStory[matchObjectBefore.id()]["lineStroke"]
        );
        console.log("story_component_match_line_" + matchObjectBefore.id());
        line = new Konva.Line({
          id: "story_component_match_line_" + matchObjectBefore.id(),
          stroke: lineColor,
          strokeWidth: lineStroke,
          lineCap: "round",
          lineJoin: "round",
          points: [x1, y1, x2, y2],
          objectType: "line",
        });
        grpMatchLines.add(line);
        line.moveToTop();

        //resetle
        matchObjectNow = null;
        matchObjectBefore = null;
        matchLiner.hide();
      }
    } else {
      //tiklanan objenin daha onceden cizgisi varsa sil
      oldLine = grpMatchLines.findOne("#story_component_match_line_" + e.id());
      if (oldLine) {
        oldLine.destroy();
      }

      var pointerPos = stage.getRelativePointerPosition();
      var x1 = (x2 = pointerPos.x);
      var y1 = (y2 = pointerPos.y);

      matchLiner.points([x1, y1, x2, y2]);
      matchLiner.moveToTop();
      matchLiner.show();
      matchObjectBefore = null;
      matchObjectNow = e;
      matchObjectState = true;
    }
  }
}

//pointerup
grpStory.on("pointerup", function () {
  if (matchObjectState) {
    matchObjectState = false;
    matchObjectNow = null;
    matchObjectBefore = null;
    matchLiner.hide();
  }
});

//pointermove
grpStory.on("pointermove", function () {
  var pointerPos = grpStory.getRelativePointerPosition();
  var x = pointerPos.x;
  var y = pointerPos.y;

  if (matchObjectState) {
    var lineColor = dataStory[matchObjectNow.id()]["lineColor"];
    var lineStroke = parseInt(dataStory[matchObjectNow.id()]["lineStroke"]);

    var matchObjectNowTargetX = parseInt(
      dataStory[matchObjectNow.id()]["targetX"]
    );
    var matchObjectNowTargetY = parseInt(
      dataStory[matchObjectNow.id()]["targetY"]
    );

    if (matchObjectNowTargetX != null) {
      var x1 = matchObjectNow.x() + matchObjectNowTargetX;
    } else {
      var x1 = matchObjectNow.x() + matchObjectNow.width() / 2;
    }
    if (matchObjectNowTargetY != null) {
      var y1 = matchObjectNow.y() + matchObjectNowTargetY;
    } else {
      var y1 = matchObjectNow.y() + matchObjectNow.height() / 2;
    }

    var x2 = x;
    var y2 = y;

    if (x1 > x2) {
      x2 += 8;
    } else {
      x2 -= 8;
    }
    if (y1 > y2) {
      y2 += 8;
    } else {
      y2 -= 8;
    }

    matchLiner.points([x1, y1, x2, y2]);
    matchLiner.stroke(lineColor);
    matchLiner.strokeWidth(lineStroke);
  }
});

function matchChecker(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 matchCheck() {
  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (obj.getAttr("data") && obj.getAttr("data")["objectType"] == "match") {
      obj.listening(false);
      var targetted = obj.getAttr("targetted");
      if (obj.getAttr("data")["target"]) {
        storyTotalObject++;
        var target = obj.getAttr("data")["target"];
        if (targetted == target) {
          matchChecker(obj, true);
          storyTotalCorrect++;
          obj.setAttr("success", true);
        } else {
          matchChecker(obj, false);
        }
      } else {
        if (targetted) {
          matchChecker(obj, false);
        }
      }
    }
  }
}

function matchSolve() {
  grpMatchLines.destroyChildren();

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

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

      obj.listening(false);

      if (obj.getAttr("data")["target"] && !obj.getAttr("solveTargetted")) {
        var target = grpStory.findOne("#" + obj.getAttr("data")["target"]);

        //sadece bir kere çizgi çizilsin obj>target yönünde
        //zaten çizilen çizgi obj>target bir daha target<obj yönünde çizilmesin
        obj.setAttr("solveTargetted", target.id());
        target.setAttr("solveTargetted", target.id());

        //object x,y
        var objectTargetX = parseInt(obj.getAttr("data")["targetX"]);
        var objectTargetY = parseInt(obj.getAttr("data")["targetY"]);

        if (objectTargetX != null) {
          var x1 = obj.x() + objectTargetX;
        } else {
          var x1 = obj.x() + obj.width() / 2;
        }

        if (objectTargetY != null) {
          var y1 = obj.y() + objectTargetY;
        } else {
          var y1 = obj.y() + obj.height() / 2;
        }

        //target x,y
        var targetTargetX = parseInt(target.getAttr("data")["targetX"]);
        var targetTargetY = parseInt(target.getAttr("data")["targetY"]);

        if (targetTargetX != null) {
          var x2 = target.x() + targetTargetX;
        } else {
          var x2 = target.x() + target.width() / 2;
        }

        if (targetTargetY != null) {
          var y2 = target.y() + targetTargetY;
        } else {
          var y2 = target.y() + target.height() / 2;
        }

        //obj nin çizgi renklerini kullan
        //diğer yönde çizgi zaten çizmicez target>obj
        var lineColor = obj.getAttr("data")["lineColor"];
        var lineStroke = parseInt(obj.getAttr("data")["lineStroke"]);

        line = new Konva.Line({
          stroke: lineColor,
          strokeWidth: lineStroke,
          lineCap: "round",
          lineJoin: "round",
          points: [x1, y1, x2, y2],
        });
        grpMatchLines.add(line);

        line.moveToTop();
      }
    }
  }
}

function matchReset() {
  objectBefore = null;
  objectNow = null;
  objectState = false;

  var objects = grpStory.getChildren();
  for (key in objects) {
    var obj = objects[key];
    if (obj.getAttr("data") && obj.getAttr("data")["objectType"] == "match") {
      obj.setAttr("targetted", "");
      obj.setAttr("solveTargetted", null);
      obj.setAttr("success", null);
      obj.listening(true);

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

  grpMatchLines.destroyChildren();
}
