let colors_html = $("#color_samples_fill div.col").clone();
$("#color_samples_stroke").append(colors_html);

let cnv, bg;
let W, H;
let global_scale3 = 1;
let t = 0;
let first_load = 1;
let bgCheck = 1;
let bg_color = "#333333";
let stroke_color = "#ffffff";
let stroke_weight = 2;
let show_labels = 1;

let fillCheck = (strokeCheck = 1);
let step = 15;
let square_bg;
let counter = (counter2 = 0);
let old_used = (force_undo = 0);
let bgImage;
let imageLoaded = 0;

let textX = (textY = txtAreaX = txtAreaY = 0);
let confirmation = 0;

let padding = 0.2;
let album_title = "";
let album_title_focus = 0;
let textW = 0;
let current_img;
let keep_aspect = 1;

let labels = [];
let total_images = initial_labels.length;
let visible_images = total_images > 0 ? total_images : 6;
let old_data = [];
let old_keep_aspect, old_img, old_label;

// For preserving aspect ratio on resize canvas
let main_aspect_ratio = 595 / 940;

let sat = 100;

W = $("#canvas_wrapper").width();
H = $("#inner_container").height();

cnv_wrapper = document.getElementById("canvas_wrapper");

let but = `<button id="but" type="button" class="btn btn-sm btn-primary bg-petrol btn-move-down edit_but" title="ΕΠΙΛΟΓΗ ΕΙΚΟΝΑΣ"    data-bs-toggle="modal"
        data-bs-target="#edit_image">
    <i class="bi bi-pencil-square small"></i>
</button>`;

let data = [];

if (!EDITABLE_LABELS) {
  $("#img_title").closest(".row").remove();
}

$("#show_labels").prop("checked", true).change();

if (!SWITCHABLE_LABELS) {
  $("#show_labels")
    .parent()
    .parent()
    .append($("#show_labels").parent().find("label"));
  $("#show_labels").parent().remove();
}

if (FIX_NUMBER_OF_IMAGES) {
  $("#visible_images").closest(".row").remove();
}

function initButtons() {
  data = [];

  if (visible_images > 6) {
    visible_images = 6;
  }

  $(".edit_but").unbind("click").remove();

  //if(initial_labels.length < 1){
  //    for(let a=0; a<6; a++){
  //        initial_labels[a] = `ΕΙΚΟΝΑ ${a+1}`
  //    }
  //}

  if (initial_labels.length < 1) {
    for (let a = 0; a < 6; a++) {
      if (a == 0) initial_labels[a] = `ΑΥΤΟΚΙΝΗΤΟ (ΝΑΙ / ΟΧΙ)`;
      if (a == 1) initial_labels[a] = `ΤΡΕΝΟ (ΝΑΙ / ΟΧΙ)`;
      if (a == 2) initial_labels[a] = `ΠΟΔΗΛΑΤΟ (ΝΑΙ / ΟΧΙ)`;
      if (a == 3) initial_labels[a] = `ΠΕΡΠΑΤΩΝΤΑΣ (ΝΑΙ / ΟΧΙ)`;
      if (a == 4) initial_labels[a] = `ΜΗΧΑΝΑΚΙ (ΝΑΙ / ΟΧΙ)`;
      if (a == 5) initial_labels[a] = `ΛΕΩΦΟΡΕΙΟ (ΝΑΙ / ΟΧΙ)`;
    }
  }

  if (initial_labels.length < visible_images) {
    for (let a = initial_labels.length; a < visible_images; a++) {
      initial_labels[a] = `ΕΙΚΟΝΑ ${a + 1}`;
    }
  }

  labels = initial_labels.slice(0, visible_images);

  for (i in labels) {
    old_img =
      old_data[i] != undefined && old_data[i]["img"] != ""
        ? old_data[i]["img"]
        : null;
    old_label = old_data[i] != undefined ? old_data[i]["label"] : labels[i];
    old_keep_aspect = old_data[i] != undefined ? old_data[i]["keep_aspect"] : 1;

    data[i] = {
      label: old_label,
      pos: [],
      img: old_img,
      keep_aspect: old_keep_aspect,
    };

    $.each(images, function (keyName, keyValue) {
      if (i == keyValue) {
        if (
          images[keyName] != undefined &&
          images_base64[keyName] != undefined &&
          first_load
        ) {
          old_img = old_img || loadImage(images_base64[keyName]);
          old_data[i] = data[i];
          data[i]["img"] = old_data[i]["img"] = old_img;
          return false;
        }
      }
    });

    but_elem = $(but);
    but_elem.attr("id", `but_${i}`).attr("title", labels[i]);
    $("#canvas_wrapper").append(but_elem);
  }

  if (old_data.length < 1) {
    old_data = data;
  }

  $(".edit_but").click(function () {
    $("#imgFile").val("");
    $("#img_preview").empty();
    imgData2 = "";
    current_img = $(this).attr("id").split("_")[1];

    if (data[current_img]["img"]) {
      $("#img_remove")
        .removeClass("visually-hidden")
        .attr("aria-hidden", "false");
    } else {
      $("#img_remove").addClass("visually-hidden").attr("aria-hidden", "true");
    }

    $("#img_title").val(data[current_img]["label"]);
  });
}

function setButtons() {
  W = cnv.width;
  H = cnv.height;

  imgW = cnv.width;
  imgH = cnv.height;

  global_scale3 = max(W / 1050, 0.58);
  padding = max(W * 0.0135, 9 * global_scale3);

  labels_count = data.length;

  switch (labels_count) {
    case 1:
      imgW = W;
      imgH = H;
      break;
    case 2:
      imgW = W / 2;
      imgH = H;
      break;
    case 3:
      imgW = W / 2;
      imgH = H / 2;
      break;
    case 4:
      imgW = W / 2;
      imgH = H / 2;
      break;
    case 5:
      imgW = W / 3;
      imgH = H / 2;
      break;
    case 6:
      imgW = W / 3;
      imgH = H / 2;
      break;
    /*  default:
            imgW = W/3
            imgH = H/2
            break; */
  }

  counter3 = 0;
  x = y = 0;

  offsetX = 0;
  offsetY = 0;

  if (album_title != "" && strokeCheck) {
    offsetY = max(4, 58 * global_scale3);
    imgH -= labels_count > 2 ? offsetY / 2 : offsetY;
  }

  for (i in data) {
    if (labels_count < 5) {
      if (i % 3 > 1) {
        y++;
      }
      x = i % 2;
    } else {
      if (i == 3) {
        y++;
      }
      x = i % 3;
    }

    if (labels_count == 3 && i == 2) {
      offsetX = (W - imgW) / 2;
    } else {
      offsetX = 0;
    }

    if (labels_count == 5 && i > 2) {
      imgW = W / 2;
    }

    data[i]["pos"] = [
      x * imgW + padding / 2 + offsetX,
      y * imgH + padding / 2 + offsetY,
      imgW - padding,
      imgH - padding,
    ];

    butX =
      data[i]["pos"][0] +
      (data[i]["pos"][2] - 10 * global_scale3 - $("#but_" + i).outerWidth()) /
        2;
    butY =
      data[i]["pos"][1] +
      (data[i]["pos"][3] - 10 * global_scale3 - $("#but_" + i).outerHeight()) /
        2.1;

    W2 = $("#canvas_wrapper").width();
    global_scale2 = W2 / W;

    $("#but_" + i).css({
      left: butX * global_scale2 + "px",
      top: butY * global_scale2 + "px",
    });
  }
}

function preload() {
  if (imgData.length < 1) {
    FIX_IMAGE = 0;
  }

  if (FIX_IMAGE) {
    bgImage = loadImage(
      imgData,
      () => {
        imageLoaded = 1;
        $(".bg_fill").empty();
      },
      () => {
        FIX_IMAGE = 0;
      },
    ); // p5js loadImage() function
  }
}

function setup() {
  bg = createGraphics(W, H);
  bg.parent(cnv_wrapper);
  bg.show();
  bg.style("position: absolute; z-index:40");

  cnv = createCanvas(W, H, cnv);
  cnv.parent(cnv_wrapper);
  //rectMode(CORNERS);
  cnv.style("position: absolute; z-index:100");

  textWrap(CHAR);
  textAlign(CENTER);

  labels = labels.slice(0, 6);

  global_scale3 = max(W / 1050, 0.58);

  initButtons();

  colorMode(HSB);

  if (init_fill_color == "") {
    fill_color = color(random(360), 50 + random(30), 70 + random(20)).toString(
      "#rrggbb",
    );
  }

  $("#fillColor").val(fill_color);

  clear();
  noStroke();
  fill(fill_color);
}

function draw() {
  labels_count = data.length;
  remove = labels_count % 2 > 1 ? 1 : 0;
  global_scale3 = max(W / 1050, 0.58);

  setButtons();

  clear();
  if (bgCheck) {
    with (bg) {
      clear();

      if (imageLoaded) {
        bg.image(
          bgImage,
          0,
          0,
          width,
          height,
          0,
          0,
          bgImage.width,
          bgImage.height,
        );
      } else {
        background(bg_color);
      }
    }
  } else {
    with (bg) {
      clear();
      background(200);
      noStroke();
      counter = 0;

      for (let x = 0; x < width; x += step) {
        counter++;
        counter2 = 0;
        for (let y = 0; y < height; y += step) {
          counter2++;
          square_bg = (counter + counter2) % 2 == 0 ? 220 : 250;
          fill(square_bg);
          square(x, y, step);
        }
      }
    }
  }

  textSize(15 * global_scale3);

  for (i in data) {
    coor = data[i]["pos"];
    fill(fill_color);

    rect(coor[0], coor[1], coor[2], coor[3], 5);

    if (data[i]["img"]) {
      keep_aspect = data[i]["keep_aspect"] ? CONTAIN : "";
      image(
        data[i]["img"],
        coor[0] + 10 * global_scale3,
        coor[1] + 10 * global_scale3,
        coor[2] - 20 * global_scale3,
        coor[3] - 20 * global_scale3,
        0,
        0,
        data[i]["img"].width,
        data[i]["img"].height,
        keep_aspect,
      );
    }

    total_textW = textWidth(data[i]["label"]);
    textW = min(coor[2] - 40 * global_scale3, total_textW);
    textX = coor[0] + 20 * global_scale3;

    if (show_labels && data[i]["label"] != "") {
      lines = ceil(total_textW / (coor[2] - 40 * global_scale3));
      rectX = coor[0] + (coor[2] - textW) / 2 - 10 * global_scale3;
      rectH = min(
        coor[3] - 20 * global_scale3,
        (lines * 21 + 11) * global_scale3,
      );
      fill("#55555590");
      rect(
        rectX,
        coor[1] + 10 * global_scale3,
        textW + 20 * global_scale3,
        rectH,
      );
    }

    fill(stroke_color);
    if (show_labels) {
      text(
        data[i]["label"],
        textX,
        coor[1] + 20 * global_scale3,
        coor[2] - 40 * global_scale3,
        coor[3] - 30 * global_scale3,
      );
    }
  }

  if (album_title != "" && strokeCheck) {
    textSize(24 * global_scale3);
    textW = textWidth(album_title);

    fill(fill_color);
    rect(padding / 2, 11 * global_scale3, W - padding, 45 * global_scale3, 5);

    fill(stroke_color);
    text(album_title, (W - textW) / 2 + textW / 2, 42 * global_scale3);
  }

  // Fix for Safari (2 of 2)
  if (sat < 100) {
    loadPixels();
    for (let i = 0; i < pixels.length; i += 4) {
      let r = pixels[i];
      let g = pixels[i + 1];
      let b = pixels[i + 2];
      let gray = (r + g + b) / 3;
      let factor = sat / 100;
      pixels[i] = r * factor + gray * (1 - factor);
      pixels[i + 1] = g * factor + gray * (1 - factor);
      pixels[i + 2] = b * factor + gray * (1 - factor);
    }
    updatePixels();
  }

  noLoop();
}

keyReleased = () => {
  /* if (keyCode == 83 && !album_title_focus && !$("#album_title").is(":focus") && !$("#img_title").is(":focus")) {
        // 83 => S Save canvas
        $("#save").click();
    } */

  if ($("#img_title").is(":focus") && keyCode == 13) {
    setTimeout(function () {
      $("#edit_yes").focus();
    }, 100);
  }
};

function resize_canvas() {
  W = $("#canvas_wrapper").width();
  if (KEEP_MAIN_ASPECT) {
    H = W * main_aspect_ratio; // based on main aspect
  } else {
    H = $("#inner_container").height();
  }

  if (first_load) {
    if (FIX_IMAGE) {
      preload();
    }

    resizeCanvas(W, H, true);
    bg.resizeCanvas(W, H, true);
    with (cnv) {
      clear();
      redraw();
    }
    first_load = 0;
  }

  cnv.style(`width: ${W}px; height: ${H}px`);
  bg.style(`width: ${W}px; height: ${H}px`);

  setButtons();
  redraw();
}

function save_canvas() {
  let format = "jpg";

  if (!bgCheck) {
    bg.clear();
    format = "png";
  }

  bg.image(cnv, 0, 0);
  saveCanvas(bg, "image_" + floor(new Date().getTime() / 1000), format);
  redraw();
}

// -------- Fill controls
$("#fillCheck").change(function () {
  fillCheck = $(this).is(":checked");
  if (!fillCheck) {
    $("#strokeCheck").prop("checked", true).change();
  }
  redraw();
});

$("#fillColor").on("input change click", function () {
  $("#color_samples_fill button").removeClass("active");
  init_fill_color = $(this).val();
  fill_color = init_fill_color;
  redraw();
});

$("#color_samples_fill button").click(function () {
  $("#color_samples_fill button").removeClass("active");
  $(this).addClass("active");

  init_fill_color = $(this).data("color");
  fill_color = init_fill_color;
});

$("#album_title").on("change keypress keyup", function () {
  album_title = $.trim($(this).val());
  setTimeout(function () {
    redraw();
  }, 300);
});

// -------- Stroke controls
$("#strokeCheck").change(function () {
  strokeCheck = $(this).is(":checked");
  if (!strokeCheck) {
    $("#fillCheck").prop("checked", true).change();
    $("#album_title").hide();
  } else {
    $("#album_title").show();
  }
  redraw();
});

$("#strokeColor").on("input change click", function () {
  $("#color_samples_stroke button").removeClass("active");
  stroke_color = $(this).val();
  redraw();
});

$("#color_samples_stroke button").click(function () {
  $("#color_samples_stroke button").removeClass("active");
  $(this).addClass("active");

  stroke_color = $(this).data("color");
});

$("#stroke_weight button").click(function () {
  $("#stroke_weight  button").removeClass("active");
  $(this).addClass("active");

  stroke_weight = $(this).data("weight");
});

$("#show_labels").change(function () {
  show_labels = $(this).is(":checked");
  redraw();
});

// -------- Number of images
$("#visible_images").val(visible_images);
$("#visible_images_label").text(visible_images);

$("#visible_images").on("input change", function () {
  visible_images = min(6, $(this).val());
  $("#visible_images_label").text(visible_images);

  initButtons();
  setButtons();
  redraw();
});

// -------- Saturation
$("#saturation_label").text($("#saturation").val());

$("#saturation").on("input change", function () {
  sat = $(this).val();
  // cnv.drawingContext.filter = `grayscale(${100-sat}%)`  // Fix for Safari (1 of 2)
  $("#saturation_label").text(sat);
  redraw();
});

// -------- Bg Fill controls
$("#removeImage").hide();

function updateImageButtons() {
  let buttonTitle = "ΕΠΙΛΟΓΗ ΕΙΚΟΝΑΣ";

  if (imageLoaded) {
    $("#loadImage").hide();
    $("#removeImage").show();
    buttonTitle = "ΑΦΑΙΡΕΣΗ ΕΙΚΟΝΑΣ";
  } else {
    $("#loadImage").show();
    $("#removeImage").hide();
  }

  $("#bg_image").attr("title", buttonTitle);
  try {
    redraw();
  } catch (err) {}
}

$("#bgCheck").change(function () {
  bgCheck = $(this).is(":checked");

  try {
    redraw();
  } catch (err) {}
});

$("#bgColor").on("input change click", function () {
  if (bg_color != $(this).val()) {
    imageLoaded = 0;
    updateImageButtons();
  }
  bg_color = $(this).val();
  try {
    redraw();
  } catch (err) {}
});

$("#bgCheck").change();
$("#bgColor").change();

$("#bg_image").click(function () {
  if (imageLoaded) {
    imageLoaded = 0;
    updateImageButtons();
  } else {
    $("#formFile").click();
  }

  try {
    redraw();
  } catch (err) {}
});

$("#formFile").change(function (e) {
  let image = e.target.files[0];
  imageLoaded = 0;

  let isImage = image.name.match(/[.]png|gif|jpg|jpeg|jfif|pjpeg|pjp$/);

  if (image && isImage) {
    let reader = new FileReader();
    reader.readAsDataURL(image);

    reader.addEventListener("load", function () {
      imgData = reader.result;
      try {
        bgImage = loadImage(imgData);
        imageLoaded = 1;
        if (!bgCheck) {
          $("#bgCheck").click();
        }
        try {
          redraw();
        } catch (err) {}
      } catch (err) {
        imageLoaded = 0;
      }
      updateImageButtons();
    });
  } else {
    updateImageButtons();
  }

  setTimeout(function () {
    try {
      redraw();
    } catch (err) {}
  }, 500);
});

$("#imgFile").change(function (e) {
  let image = e.target.files[0];

  let isImage = image.name.match(/[.]png|gif|jpg|jpeg|jfif|pjpeg|pjp$/);
  imgData2 = "";

  if (image && isImage) {
    let reader = new FileReader();
    reader.readAsDataURL(image);

    reader.addEventListener("load", function () {
      imgData2 = reader.result;
      try {
        if (imgData2 != "") {
          $("#img_preview")
            .empty()
            .append(
              `<img src="${imgData2}" alt="Προεπισκόπηση εικόνας" style="width:100%"/>`,
            );
          $("#img_remove")
            .removeClass("visually-hidden")
            .attr("aria-hidden", "false");
        }
      } catch (err) {}
    });
  }
});

const confirmModal = document.getElementById("confirm");

confirmModal.addEventListener("shown.bs.modal", (event) => {
  $("#confirm_yes").focus();
});

confirmModal.addEventListener("hidden.bs.modal", (event) => {
  if (confirmation) {
    $("#alert").text("Το περιεχόμενο διαγράφηκε");
    cnv.background(bg_color);
    first_load = 1;
    imageLoaded = 0;
    resize_canvas();
    confirmation = 0;
    updateImageButtons();

    for (i in data) {
      data[i]["img"] = "";
    }
    for (i in old_data) {
      old_data[i]["img"] = "";
    }

    redraw();
  }
});

$("#confirm button").click(function () {
  confirmation = $(this).data("confirm");
});

$("#clear").click(function () {
  $("#confirm").modal("show");
});

$("#save").click(function () {
  save_canvas();
});

// ----------------  Edit image modal
const edit_imageModal = document.getElementById("edit_image");

edit_imageModal.addEventListener("shown.bs.modal", (event) => {
  confirmation = 0;

  $("#img_preview").empty();

  if (data[current_img]["img"]) {
    img_data = data[current_img]["img"].canvas.toDataURL("image/jpeg");
    $("#img_preview").append(
      `<img src="${img_data}" alt="Εικόνα ${parseInt(current_img) + 1}" style="width:100%"/>`,
    );
  }

  $("#keep_aspect").prop("checked", data[current_img]["keep_aspect"]);
});

edit_imageModal.addEventListener("hidden.bs.modal", (event) => {
  if (confirmation) {
    confirmation = 0;
    if (data.length == 6) {
      old_data = data;
    }

    if (EDITABLE_LABELS) {
      data[current_img]["label"] = $.trim($("#img_title").val());
      $("#but_" + current_img).attr("title", data[current_img]["label"]);
    }

    if ($("#img_remove").hasClass("visually-hidden")) {
      data[current_img]["img"] = "";
      imgData2 = "";
    }

    if (imgData2 != "") {
      data[current_img]["img"] = loadImage(imgData2);
    }

    data[current_img]["keep_aspect"] = $("#keep_aspect").is(":checked") ? 1 : 0;

    old_data[current_img] = data[current_img];

    setTimeout(function () {
      try {
        redraw();
      } catch (err) {}
    }, 500);
  }
});

$("#edit_image button").click(function () {
  confirmation = $(this).data("confirm");
});

function init_controls() {
  $("#pencil").click().attr("aria-pressed", "true");
  $("#color_samples_stroke .btn-info, #color_samples_fill .btn-warning")
    .click()
    .addClass("active")
    .attr("aria-pressed", "true");

  if (!$("#fillCheck").is(":checked")) {
    $("#fillCheck").prop("checked", true);
  }
  if (!$("#strokeCheck").is(":checked")) {
    $("#strokeCheck").prop("checked", true);
  }

  if (!$("#bgCheck").is(":checked")) {
    $("#bgCheck").click();
  }

  $("#fillColor").val(fill_color);
  $("#strokeColor").val(stroke_color);
  $("#bgColor").val(bg_color);

  $("#album_title").change();
}
