$(function() {
  let frame = $(".frame")
  let frameWidth = frame.attr("w")
  let frameHeight = frame.attr("h")
  let frameBorder = frame.attr("b")

  let frameAngle = frame.find("img.frame-angle").detach()
  let frameBorderTop = frame.find("img.frame-border-top").detach()
  let frameBorderRight = frame.find("img.frame-border-right").detach()

  let frameInsideBorderSize = $("#frame-box #frame-inside-border-size").val()
  let frameInsideBorder = $("#frame-box #frame-inside-border").val()

  frame.css({
    "width": frameWidth,
    "height": frameHeight,
    "padding": frameBorder / 2 - 1,
  })

  rerenderFrame()
  function rerenderFrame(frameBox = frame, width = frameWidth, height= frameHeight) {
    frameBox.css({
      "width": width,
      "height": height
    })
  }

  makeFrameAngles(frame)
  function makeFrameAngles(frame, frameAngleCopy = frameAngle) {
    frame.find('img.frame-angle').remove();

    for (var i = 0; i < 4; i++) {
      var clonedAngle = frameAngleCopy.clone();
      var rotationAngle = i * 90;

      clonedAngle.css({
        "width": frameBorder,
        "height": frameBorder,
        "transform": "rotate(" + rotationAngle + "deg)"
      });

      switch (i) {
        case 0:
           clonedAngle.addClass("frame-angle-top-left");
          break;
        case 1:
            clonedAngle.addClass("frame-angle-top-right");
          break;
        case 2:
            clonedAngle.addClass("frame-angle-bottom-right");
          break;
        case 3:
            clonedAngle.addClass("frame-angle-bottom-left");
          break;
        default:
          break;
      }
      frame.append(clonedAngle);
    }
  }

  makeFrameBorders(frame)
  function makeFrameBorders(frame, frameBorderTopCopy = frameBorderTop, frameBorderRightCopy = frameBorderRight){
    frame.find('div.frame-border').remove();

    for (var i = 0; i < 4; i++) {
      var emptyDiv = $("<div class='frame-border'></div>");
      var rotationAngle = i * 90;

      if ((i == 0 ) || (i == 2)) {
        emptyDiv.css({
          "width": "calc(100% - " + frameBorder * 2 + "px + 2px)",
          "height": frameBorder / 2 + "px",
          "transform": "rotate(" + rotationAngle + "deg)",
          "background-image": "url(" + frameBorderTopCopy.attr('src') + ")",
        })
      } else {
        emptyDiv.css({
          "width": frameBorder / 2 + "px",
          "height": "calc(100% - " + frameBorder * 2 + "px + 2px)",
          "background-image": "url(" + frameBorderRightCopy.attr('src') + ")",
        })
      }

      switch (i) {
        case 0:
            emptyDiv.addClass("frame-border-top");
            emptyDiv.css({
              "left": "calc(" + frameBorder + "px - 1px)",
              "top": 0,
            })
          break;
        case 1:
            emptyDiv.addClass("frame-border-right");
            emptyDiv.css({
              "top": "calc(" + frameBorder + "px - 1px)",
              "right": 0,
            })
          break;
        case 2:
            emptyDiv.addClass("frame-border-bottom");
            emptyDiv.css({
              "left": "calc(" + frameBorder + "px - 1px)",
              "bottom": 0,
            })
          break;
        case 3:
            emptyDiv.addClass("frame-border-left");
            emptyDiv.css({
              "top": "calc(" + frameBorder + "px - 1px)",
              "left": 0,
            })
          break;
        default:
          break;
      }
      frame.append(emptyDiv);
    }
  }

  //* Frame panel images handler
  $('#input-frame-image-btn').on('change', function(e) {
    var file = e.target.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      var imageUrl = e.target.result;
      addImageToFrame(imageUrl)
    };
    reader.readAsDataURL(file);
  });

  function addImageToFrame(imageUrl) {
    frameWidth =$("#input-frame-width").val();
    frame.find('img.frame-image').remove();

    var imgElement = $('<img>');
    imgElement.attr('src', imageUrl);
    imgElement.attr('class', 'frame-image');
    imgElement.attr('style', `height: calc(${frameHeight}px - 49px * 2 - ${frameInsideBorderSize * 2}px); margin: ${frameInsideBorderSize}px;`);
    frame.append(imgElement[0]);

    imgElement.on('load', function() {
      let newFrameWidth = parseInt(imgElement.width()) + (49 * 2) + (parseInt(frameInsideBorderSize) * 2)
      rerenderFrame(frame, newFrameWidth, frameHeight)
      $("#input-frame-img-width").val(imgElement.width() + (49 * 2))
    });
  }


  //? Frame panel (controllers)
  //* Frame: input width
  $("#input-frame-width").on('change', function() {
    frameWidth = $(this).val();
    var minValue = parseInt($(this).attr('min'));
    var maxValue = parseInt($(this).attr('max'));

    if (frameWidth < minValue) {
      $(this).val(minValue);
      frameWidth = minValue
    }
    if (frameWidth > maxValue) {
      $(this).val(maxValue);
      frameWidth = maxValue
    }

    $(this).siblings(".frame-panel-tile-text").find('span').text(frameWidth)
    rerenderFrame(frame, frameWidth, frameHeight)
  })

  //* Frame: input height
  $("#input-frame-height").on('change', function() {
    frameHeight = $(this).val();
    var minValue = parseInt($(this).attr('min'));
    var maxValue = parseInt($(this).attr('max'));

    if (frameHeight < minValue) {
      $(this).val(minValue);
      frameHeight = minValue
    }
    if (frameHeight > maxValue) {
      $(this).val(maxValue);
      frameHeight = maxValue
    }

    $(this).siblings(".frame-panel-tile-text").find('span').text(frameHeight)
    rerenderFrame(frame, frameWidth, frameHeight)
  })

  //* Frame: input border
  $("#input-frame-border").on('change', function() {
    frameBorder = $(this).val();
    $(this).siblings(".frame-panel-tile-text").find('span').text(frameBorder)
    rerenderFrame()
    makeFrameAngles(frame)
    makeFrameBorders(frame)
  })

  $("#input-frame-img-height").on('change', function() {
    var frameImg = $('.frame-image');
    frameHeight = $(this).val();

    frameImg.css({
      "height": `calc(${$(this).val()}px - 49px * 2)`
    })
    rerenderFrame(frame, frameWidth, frameHeight)
  })
  $("#input-frame-img-width").on('change', function() {
    var frameImg = $('.frame-image');
    frameWidth = $(this).val();

    frameImg.css({
      "width": `calc(${$(this).val()}px - 49px * 2)`
    })
    rerenderFrame(frame, frameWidth, frameHeight)
  })

  //* Frame: image inside border size
  $("#frame-inside-border-size").on('change', function() {
    frameInsideBorderSize = $(this).val();

    let frameImg = $(".frame-image", frame)

    frameImg.css({
      'height': `calc(${frameHeight}px - 49px * 2 - ${frameInsideBorderSize * 2}px)`,
      'margin': `${frameInsideBorderSize}px`
    });
    let newFrameWidth = parseInt(frameImg.width()) + (49 * 2) + (parseInt(frameInsideBorderSize) * 2)
    rerenderFrame(frame, newFrameWidth, frameHeight)
    $("#input-frame-img-width").val(imgElement.width() + (49 * 2))
  })

    //* Frame: image inside border
    $("#frame-inside-border").on('change', function() {
      frameInsideBorder = $(this).val();

      let frameImg = $(".frame-image", frame)

       frameImg.toggleClass('border')
    })
})