if (!window?.isParsedProduct)
  if (window?.location?.pathname?.split("/")) {
    if (window?.location?.pathname?.split("/").length === 3) {
      if (window?.location?.pathname?.split("/")[1] === "products") {
        let productDataUrl = window.location.origin + window.location.pathname + ".json";
        parseProductData(productDataUrl);
        window.isParsedProduct = true
      }
    }else if (window?.location?.pathname?.split("/").length === 5) {
        if (window?.location?.pathname?.split("/")[3] === "products") {
          let productDataUrl = window.location.origin + window.location.pathname + ".json";
          parseProductData(productDataUrl);
          window.isParsedProduct = true
        }
    }
    else if (window?.location?.pathname?.split("/").length === 7) {
      if (window?.location?.pathname?.split("/")[5] === "products") {
        let productDataUrl = window.location.origin + window.location.pathname + ".json";
        parseProductData(productDataUrl);
        window.isParsedProduct = true
      }
    }
  }

function parseProductData(url) {

  let xhr;
  // code for IE7+, Firefox, Chrome, Opera, Safari
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  }
  // code for IE6, IE5
  else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let data = JSON.parse(xhr.responseText);
      fetchTeelaunchProductMetaFileds(data?.product?.id);
    }
  }
  xhr.open("GET", url, false);
  xhr.send();
}

/**
 * the Role of this function is to make a request to teelaunch end
 * fetch the sizing chart or custom inputs
 * @param productId
 */
function fetchTeelaunchProductMetaFileds(productId) {
  let xhr;
  let url = "https://app.teelaunch.com/api/v1/shopify/product/meta/" + productId;
  // code for IE7+, Firefox, Chrome, Opera, Safari
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();

  }
  // code for IE6, IE5
  else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let data = JSON.parse(xhr.responseText);
      if (data?.sizing_chart?.length > 0) {
        addSizingChartDesign(data.sizing_chart);
      }

      if (data?.inputs?.length > 0) {
        window.teeOptions =     data?.options;
        addInputs(data?.inputs)
        // disableByShareButton(data?.options, getFormIds(), true)
      }
    }
  }

  xhr.open("GET", url, false);
  xhr.send();
}




function merge(originalData, missingData, headers) {


  let initializer = {id: "id"}
  let emptyArray = []

  for (let i = 0; i < headers.length; i++) {
    Object.assign(initializer, {[`column_${i + 1}_value`]: ""})
  }

  for (let s = 0; s < missingData.length; s++) {
    emptyArray.push(initializer)
  }

  const finalMap = emptyArray.map((value, index) => ({...value, option: missingData[index]}))

  return originalData.concat(finalMap)
}


function prepareChartBlock(data) {

  //each row will contain three factors
  allOptions = []
  arrayofInches = []
  arrayofCms = []
  arrayOfSizes = []
  let headers = data.headers

  const infoChartUnit = data.info_chart_units[0];

  inchesRows = infoChartUnit.blank_info_chart_unit[0].blank_info_chart_rows
  cmRows = infoChartUnit.blank_info_chart_unit[1].blank_info_chart_rows
  sizesRows = infoChartUnit.blank_info_chart_unit[2].blank_info_chart_rows

  // get for each unit its own abbreviation
  inchesAbbreviation = infoChartUnit.blank_info_chart_unit[0].abbreviation
  cmAbbreviation = infoChartUnit.blank_info_chart_unit[1].abbreviation
  sizeAbbreviation = infoChartUnit.blank_info_chart_unit[2].abbreviation

  //get the array of options each one on a side
  for (var b = 0; b < 3; b++) {
    for (var s = 0; s < infoChartUnit.blank_info_chart_unit[b].blank_info_chart_rows.length; s++) {
      if (b === 0) {
        arrayofInches.push(infoChartUnit.blank_info_chart_unit[b].blank_info_chart_rows[s].blank_option_value.name)
      } else if (b === 1) {
        arrayofCms.push(infoChartUnit.blank_info_chart_unit[1].blank_info_chart_rows[s].blank_option_value.name)
      } else {
        arrayOfSizes.push(infoChartUnit.blank_info_chart_unit[2].blank_info_chart_rows[s].blank_option_value.name)
      }
    }
  }

  // get all the options for example [S,M,L,XL] it comes sorted
  for (var i = 0; i < data.options.length; i++) {
    allOptions.push(data.options[i].name);
  }

  //append for each object his own option
  arrayofInches = inchesRows.map((element, index) => ({
    ...element,
    option: arrayofInches[index]
  }))


  arrayofCms = cmRows.map((element, index) => ({
    ...element,
    option: arrayofCms[index]
  }))

  arrayOfSizes = sizesRows.map((element, index) => ({
    ...element,
    option: arrayOfSizes[index]
  }))

  // get for each option the missing sizes types
  missingInches = allOptions.filter(x => !arrayofInches.find(f => f.option == x))
  missingCms = allOptions.filter(x => !arrayofCms.find(f => f.option == x))
  missingsizes = allOptions.filter(x => !arrayOfSizes.find(f => f.option == x))


  //add the missing types to the array of inches sizes and centimeters
  inchesRows = merge(arrayofInches, missingInches, headers);
  cmRows = merge(arrayofCms, missingCms, headers);
  sizesRows = merge(arrayOfSizes, missingsizes, data.headers);

  // set all types in the right orders to set each data in it's right row
  inchesRows = allOptions.map((i) => inchesRows.find((j) => j.option === i));
  cmRows = allOptions.map((i) => cmRows.find((j) => j.option === i));
  sizesRows = allOptions.map((i) => sizesRows.find((j) => j.option === i));


  let buffer = `<html><head>
    <style>
    table {
    border-collapse: collapse;
     width: 100%;
     border: 10px solid black;
    }

    th, td {
    text-align: left;
    padding: 8px;
    border: 10px solid black;
    }

    </style>
    </head>
    <body>
    <table border="1">
    <tr>
    <th scope="col" colspan="1">${data.name}</th>`

  for (var i = 0; i < headers.length; i++) {
    buffer += `<th  scope="col" colSpan="1">${headers[i] ?? ""}</th>`;
  }
  buffer += "</tr>"


  for (var i = 0; i < data.options.length; i++) {
    buffer += `<tr scope="row">&nbsp;`
    buffer += `<td>${allOptions[i]}</td>`
    for (var j = 0; j < data.headers.length; j++) {
      buffer += `<td>
         ${inchesRows[i][`column_${j + 1}_value`] ? `${inchesAbbreviation} : ${inchesRows[i][`column_${j + 1}_value`]}<br>` : ""}
         ${cmRows[i][`column_${j + 1}_value`] ? `${cmAbbreviation} : ${cmRows[i][`column_${j + 1}_value`]}<br>` : ""}
         ${sizesRows[i][`column_${j + 1}_value`] ? `${sizeAbbreviation} : ${sizesRows[i][`column_${j + 1}_value`]}<br>` : ""}
          </td>`
    }
    buffer += `</tr>`
  }

  buffer += `
    </body>
    </table>
    </html>`
  return buffer;
}

function teelaunchSizingChartTrigger() {

  let element = document.getElementById("teelaunch-sizing-chart");
  let style = element.style;

  if (style.display === "block") {
    element.style.display = "none";
  } else {
    element.style.display = "block";
  }
}

function addInputs(inputs) {
  // get the add/car elements
  let formIds = getFormIds();
  formIds.forEach((formId)=>{
    let element  = document.getElementById(formId);
    let personalize = "<div>"
    inputs.forEach((input) => {
      //draw the personlised input
      personalize += drawInput(input, formIds)
      // draw all inputsd
      personalize += "</div>"
      let temp = document.createElement("div");
      temp.innerHTML = personalize;
      element?.prepend(temp.firstChild)
    })
    disableBuyAddCartButton(window.teeOptions,formId,true)
  })

}

/**
 * The role of this function is to draw the sizing chart of a given elements
 * @param data
 */
function addSizingChartDesign(data) {

  let personalize = '';

  personalize += '<div href="javascript:;" style="margin-top: 10px " class="shopify-payment-button__more-options" onclick="teelaunchSizingChartTrigger()">View Sizing Chart</div>'
  personalize += '<div id="teelaunch-sizing-chart" class="teelaunch-sizing-chart" style="display: none">'
  for (var i = 0; i < data.length; i++){
    personalize += prepareChartBlock(data[i]);
  }
  personalize += '</div>'
  let temp = document.createElement("div");
  temp.innerHTML = personalize;
  document.getElementsByClassName('shopify-payment-button')[0].parentElement.append(temp);
}


function drawInput(data, formId ) {
  return `<div>
              <div class="field" style="margin-bottom: 10px">
              <input onkeyup="onChangePersonalize()" onkeydown="onChangePersonalize()"  class="search__input field__input" id="${data.value}" type="text" name="properties[${data.value}]" placeholder=${data.value} form="${formId}"  ></div>
         </div>`
}

function getFormIds() {

  let forms = document.querySelectorAll("form[action='/cart/add']")
  let formIds = [];
  if (forms && forms.length == 1)
  {
    formIds.push(forms[0].getAttribute("id"));
  }
  // Find the id in case the form which hold the data contains input with status not hidden
  // The quantity input is always required!! for any ecommerce
  forms?.forEach((form) => {
    let elements = form?.elements;
    for (const key in elements) {
      if (elements.hasOwnProperty(key)) {
        const type = elements[key].type
        if(type != "hidden")
        {
          formIds.push(form.getAttribute("id"))
          continue;
        }
      }
    }
  })
  let ids = formIds.filter((value,index,array)=>{
    return array.indexOf(value) === index;
  })
  return ids;
}

function disableBuyAddCartButton(excludeOptions, formId , disable ) {
  let addToCartElements = document.getElementById(formId)
  for (const key in addToCartElements) {
    if (addToCartElements.hasOwnProperty(key)) {
      const name = addToCartElements[key]?.name
      const id   = addToCartElements[key]?.id
      if (!excludeOptions.includes(name) && !excludeOptions.includes(id) ) {
        addToCartElements[key].disabled = disable;
      }
    }
  }
}

function onChangePersonalize()
{
  const value =   document?.getElementById("Custom Text").value
  const formIds = getFormIds();
  formIds?.forEach((formId)=>{
    disableBuyAddCartButton(window.teeOptions,formId,!(value?.length > 0))
  })

}





