/* Project specific Javascript goes here. */
function onPositionSelectChange(elem) {
  elem.querySelectorAll("option").forEach((option) => {
    if (option.innerText == elem.value) {
      option.setAttribute("selected", "selected");
    } else {
      option.removeAttribute("selected");
    }
  });
  colorPositions();
  refreshLineupOrder();
}

function togglePopup(el) {
  el.querySelector(".Popup-container").classList.toggle("is-open");
}

function colorPositions() {
  for (bcLineup of document.getElementsByClassName("event-lineup")) {
    selected_lineup_positions = Array.from(
      bcLineup.querySelectorAll(".Panel-row .SelectBox.position-selection option[selected='selected']")
    ).map((el) => el.value);
    for (position_status of bcLineup.querySelectorAll(".position-status")) {
      for (class_name of ["text-danger", "text-warning", "text-success"]) {
        position_status.classList.remove(class_name);
      }

      occurrences = selected_lineup_positions.filter((s) => s == position_status.innerText).length;

      if (occurrences == 1) {
        position_status.classList.add("text-success");
      } else if (occurrences > 1) {
        position_status.classList.add("text-warning");
      } else {
        position_status.classList.add("text-danger");
      }
    }
  }
}

function refreshLineupOrder() {
  Array.from(document.querySelectorAll(".event-lineup")).forEach((bcLineup) => {
    Array.from(
      bcLineup.querySelectorAll(
        ".event-lineup .starting .lineup-slot, \
         .event-lineup .position-only .lineup-slot, \
         .event-lineup .bench .lineup-slot"
      )
    ).forEach((slot, i) => {
      slot.querySelector("input[name*=sequence]").value = i;
      selected_position = slot.querySelector("option[selected='selected']");
      if (selected_position && selected_position.text != "--") {
        slot.querySelector("input[name*=label]").value = selected_position.text;
      } else {
        slot.querySelector("input[name*=label]").value = null;
      }
    });
    Array.from(
      bcLineup.querySelectorAll(
        ".event-lineup .position-only .lineup-slot, \
         .event-lineup .bench .lineup-slot"
      )
    ).forEach((slot) => {
      selected_position = slot.querySelector("option[selected='selected']");
      if (selected_position && selected_position.text != "--") {
        slot.querySelector("input[name*=label]").value = `${selected_position.text} [PO]`;
      }
    });
  });
}

function refresh_lineup_order(itemEl) {
  let bcLineup = itemEl.closest(".benchcoach-lineup");
  var player_rows = [];
  for (tbody of bcLineup.querySelectorAll("[class*='tbody-benchcoach-starting']")) {
    for (row of tbody.rows) {
      player_rows.push(row);
    }
  }

  for (let i = 0; i < player_rows.length; i++) {
    var player_order = player_rows[i].querySelector('[id^="sequence"]');
    var form_element_order = player_rows[i].querySelector('[id$="sequence"]');
    player_order.innerText = parseInt(player_rows[i].dataset.order);
    player_rows[i].dataset.order = i;
    form_element_order.value = i;
    player_order.innerHTML = i + 1;
  }
  var player_rows = bcLineup.getElementsByClassName("tbody-benchcoach-bench")[0].rows;
  for (let i = 0; i < player_rows.length; i++) {
    var player_order = player_rows[i].querySelector('[id^="sequence"]');
    var form_element_order = player_rows[i].querySelector('[id$="sequence"]');
    player_rows[i].dataset.order = null;
    form_element_order.value = null;
    player_order.innerHTML = null;
  }
}

for (bcLineup of document.querySelectorAll(".event-lineup")) {
  console.log();
  options = {
    animation: 150,
    handle: ".Panel-cell:has(.drag-handle), .Panel-cell:has(.sequence)",
    ghostClass: "ghost",
    group: {
      name: bcLineup.id,
      put: [bcLineup.id],
      pull: [bcLineup.id],
    },
    onAdd: function (/**Event*/ evt) {
      console.log("added to lineup");
      // Add to Lineup
      var itemEl = evt.item; // dragged HTMLElement

      refreshLineupOrder();
    },
    onUpdate: function (/**Event*/ evt) {
      console.log("update to lineup");
      // var itemEl = evt.item; // dragged HTMLElement
      // refresh_lineup_order(itemEl);
      refreshLineupOrder();
    },
  };
  new Sortable.create(bcLineup.querySelector(".starting .slot-set"), options);
  new Sortable.create(bcLineup.querySelector(".position-only .slot-set"), options);
  options["sort"] = false;
  new Sortable.create(bcLineup.querySelector(".bench .slot-set"), options);
}

function copyEmailTable(itemEl, subject, recipients) {
  // Create container for the HTML
  // [1]
  let bcLineup = itemEl.closest(".benchcoach-lineup");
  var container = document.createElement("div");
  var tbl = document.createElement("table");

  let thead = tbl.createTHead();
  let thead_row = thead.insertRow();
  let thead_row_cell = thead_row.insertCell();
  thead_row_cell.appendChild(document.createElement("h3").appendChild(document.createTextNode("STARTING LINEUP")));
  thead_row_cell.colSpan = 3;
  thead_row_cell.classList.add("title-cell");
  var tbody = tbl.createTBody();
  for (row of bcLineup.querySelector(".table-benchcoach-startinglineup").rows) {
    let tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.classList.add("sequence-cell");
    cell.appendChild(document.createTextNode(parseInt(row.dataset.order) + 1));
    cell = tr.insertCell();
    cell.appendChild(document.createTextNode(row.dataset.playerName));
    cell.classList.add("name-cell");
    tr.insertCell().appendChild(document.createTextNode(row.dataset.position));
  }

  if (bcLineup.querySelector(".table-benchcoach-startingpositionalonly").rows.length > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("STARTING (POS. ONLY)"));
    cell.classList.add("title-cell");

    for (row of bcLineup.querySelector(".table-benchcoach-startingpositionalonly").rows) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");
      cell.appendChild(document.createTextNode(""));
      cell = tr.insertCell();
      cell.appendChild(document.createTextNode(row.dataset.playerName));
      cell.classList.add("name-cell");
      tr.insertCell().appendChild(document.createTextNode(row.dataset.position));
    }
  }

  if (bcLineup.querySelector(".table-benchcoach-bench").rows.length > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("SUBS"));
    cell.classList.add("title-cell");

    for (row of bcLineup.querySelector(".table-benchcoach-bench").rows) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");
      availability_status = {
        None: "UNK",
        0: "NO",
        2: "MAY",
        1: "YES",
      }[row.dataset.availabilityStatuscode];
      cell.appendChild(document.createTextNode(availability_status));
      cell = tr.insertCell();
      cell.appendChild(document.createTextNode(row.dataset.playerName));
      cell.classList.add("name-cell");
      tr.insertCell().appendChild(document.createTextNode(""));
    }
  }

  if (bcLineup.querySelector(".table-benchcoach-out").rows.length > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("OUT"));
    cell.classList.add("title-cell");

    for (row of bcLineup.querySelector(".table-benchcoach-out").rows) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");
      availability_status = {
        None: "UNK",
        0: "NO",
        1: "MAY",
        2: "YES",
      }[row.dataset.availabilityStatuscode];
      cell.appendChild(document.createTextNode(availability_status));
      tr.insertCell().appendChild(document.createTextNode(row.dataset.playerName));
      tr.insertCell().appendChild(document.createTextNode(""));
    }
  }

  container.appendChild(tbl);
  for (cell of container.getElementsByClassName("title-cell")) {
    cell.setAttribute("style", "font-weight:bold;background-color:#323669;color:#fff;padding:2px 5px;");
  }

  for (cell of container.getElementsByClassName("sequence-cell")) {
    cell.setAttribute("style", "font-weight:bold;padding:2px 5px;");
  }

  for (cell of container.getElementsByClassName("name-cell")) {
    cell.setAttribute("style", "width:200px;");
  }

  // Detect all style sheets of the page
  var activeSheets = Array.prototype.slice.call(document.styleSheets).filter(function (sheet) {
    return !sheet.disabled;
  });

  // Mount the container to the DOM to make `contentWindow` available
  // [3]
  document.body.appendChild(container);

  // Copy to clipboard
  // [4]
  window.getSelection().removeAllRanges();

  var range = document.createRange();
  range.selectNode(container);
  window.getSelection().addRange(range);

  // [5.1]
  document.execCommand("copy");

  // [5.2]
  for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;

  // [5.3]
  // document.execCommand('copy')

  // [5.4]
  for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = false;

  // Remove the container
  // [6]
  document.body.removeChild(container);
  subject_encoded = encodeURIComponent(subject);
  window.open("readdle-spark://compose?recipient=manager@chihounds.com&subject=" + subject + "&bcc=" + recipients);
}

function emailModal(el, url) {
  form = el.closest("form");
  console.log(url);
  data = new FormData(form);
  console.log(data);
  console.log(form);

  email_modal = document.querySelector("#email-modal");

  fetch(url, {
    method: "POST",
    body: data,
  })
    .then((response) => {
      if (response.ok) {
        return response.text();
      } else {
        return Promise.reject(response.text());
      }
    })
    .then((text) => {
      email_modal.classList.add("is-open");
      email_modal.querySelector(".Modal-body").innerHTML = text;
    });
}

function onSubmit(form, event) {
  event.preventDefault();
  waiting_message = document.querySelector("#waiting-message.Feedback");
  success_message = document.querySelector("#success-message.Feedback");
  failure_message = document.querySelector("#failure-message.Feedback");
  data = new FormData(form);
  url = form.attributes.action.textContent;
  waiting_message.classList.remove("u-hidden");
  fetch(url, {
    method: "POST",
    body: data,
  })
    .then((response) => {
      waiting_message.classList.add("u-hidden");
      if (response.ok) {
        return response.text();
      } else {
        return Promise.reject(response.text());
      }
    })
    .then((text) => {
      success_message.classList.remove("u-hidden");
      success_message.querySelector("span.message").innerHTML = text;
    })
    .catch((error) => {
      failure_message.classList.remove("u-hidden");
      console.log(error);
      success_message.querySelector("span.message").innerHTML = error;
      waiting_message.classList.add("u-hidden");
    });
}

function copyEmailTable(itemEl, subject, recipients) {
  // Create container for the HTML
  // [1]
  let bcLineup = itemEl.closest(".event-lineup");
  console.log(bcLineup);
  var container = document.createElement("div");
  var tbl = document.createElement("table");

  let thead = tbl.createTHead();
  let thead_row = thead.insertRow();
  let thead_row_cell = thead_row.insertCell();
  thead_row_cell.appendChild(document.createElement("h3").appendChild(document.createTextNode("STARTING LINEUP")));
  thead_row_cell.colSpan = 3;
  thead_row_cell.classList.add("title-cell");
  var tbody = tbl.createTBody();

  lineup_slots_starting = bcLineup.querySelectorAll(".starting .slot-set .lineup-slot");

  for (node of lineup_slots_starting) {
    console.log("node", node);
    let tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.classList.add("sequence-cell");
    sequence = node.querySelector("input[name*='sequence']").value;
    console.log(sequence);
    cell.appendChild(document.createTextNode(parseInt(sequence) + 1));
    name = node.querySelector("div:has(.lastname)");
    cell = tr.insertCell();
    cell.appendChild(document.createTextNode(name.textContent));
    cell.classList.add("name-cell");
    position_label = node.querySelector("input[name*='label']").value;
    tr.insertCell().appendChild(document.createTextNode(position_label));
  }

  lineup_slots_position_only = bcLineup.querySelector(".position-only .slot-set .lineup-slot");
  console.log("lineup slots position", lineup_slots_position_only);
  if (lineup_slots_position_only.length > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("STARTING (POS. ONLY)"));
    cell.classList.add("title-cell");

    for (node of lineup_slots_position_only) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");
      cell.appendChild(document.createTextNode(""));
      cell = tr.insertCell();
      name = node.querySelector("div:has(.lastname)");
      cell.appendChild(document.createTextNode(name.textCotent));
      cell.classList.add("name-cell");
      position_label = node.querySelector("input[name*='label']").value;
      tr.insertCell().appendChild(document.createTextNode(position_label));
    }
  }

  lineup_slots_bench = bcLineup.querySelector(".bench .slot-set .lineup-slot");
  if (lineup_slots_bench > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("SUBS"));
    cell.classList.add("title-cell");

    for (node of lineup_slots_bench) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");

      div_avail_code = node.querySelector("div[class*='availability-status-code']");
      if (div_with_avail_code.classList.includes("availability-status-code-1")) {
        cell.appendChild(document.createTextNode("YES"));
      } else if (div_with_avail_code.classList.includes("availability-status-code-2")) {
        cell.appendChild(document.createTextNode("MAY"));
      } else if (div_with_avail_code.classList.includes("availability-status-code-0")) {
        cell.appendChild(document.createTextNode("NO"));
      } else {
        cell.appendChild(document.createTextNode("UNK"));
      }
      cell = tr.insertCell();
      name = node.querySelector("div:has(.lastname)");
      cell.appendChild(document.createTextNode(name.textCotent));
      cell.classList.add("name-cell");
      tr.insertCell().appendChild(document.createTextNode(""));
    }
  }

  lineup_slots_out = bcLineup.querySelector(".out .slot-set .lineup-slot");
  if (lineup_slots_out > 0) {
    var tr = tbody.insertRow();
    cell = tr.insertCell();
    cell.colSpan = 3;
    cell.appendChild(document.createTextNode("OUT"));
    cell.classList.add("title-cell");

    for (node of lineup_slots_out) {
      var tr = tbody.insertRow();
      cell = tr.insertCell();
      cell.classList.add("sequence-cell");
      div_avail_code = node.querySelector("div[class*='availability-status-code']");
      if (div_with_avail_code.classList.includes("availability-status-code-1")) {
        cell.appendChild(document.createTextNode("YES"));
      } else if (div_with_avail_code.classList.includes("availability-status-code-2")) {
        cell.appendChild(document.createTextNode("MAY"));
      } else if (div_with_avail_code.classList.includes("availability-status-code-0")) {
        cell.appendChild(document.createTextNode("NO"));
      } else {
        cell.appendChild(document.createTextNode("UNK"));
      }
      cell = tr.insertCell();
      name = node.querySelector("div:has(.lastname)");
      cell.appendChild(document.createTextNode(name.textCotent));
      cell.classList.add("name-cell");
      tr.insertCell().appendChild(document.createTextNode(""));
    }
  }

  container.appendChild(tbl);
  for (cell of container.getElementsByClassName("title-cell")) {
    cell.setAttribute("style", "font-weight:bold;background-color:#323669;color:#fff;padding:2px 5px;");
  }

  for (cell of container.getElementsByClassName("sequence-cell")) {
    cell.setAttribute("style", "font-weight:bold;padding:2px 5px;");
  }

  for (cell of container.getElementsByClassName("name-cell")) {
    cell.setAttribute("style", "width:200px;");
  }

  // Detect all style sheets of the page
  var activeSheets = Array.prototype.slice.call(document.styleSheets).filter(function (sheet) {
    return !sheet.disabled;
  });

  // Mount the container to the DOM to make `contentWindow` available
  // [3]
  document.body.appendChild(container);

  // Copy to clipboard
  // [4]
  window.getSelection().removeAllRanges();

  var range = document.createRange();
  range.selectNode(container);
  window.getSelection().addRange(range);

  // [5.1]
  document.execCommand("copy");

  // [5.2]
  for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;

  // [5.3]
  // document.execCommand('copy')

  // [5.4]
  for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = false;

  // Remove the container
  // [6]
  document.body.removeChild(container);
  subject_encoded = encodeURIComponent(subject);
  window.open("readdle-spark://compose?recipient=manager@chihounds.com&subject=" + subject + "&bcc=" + recipients);
}
