var tempVal;
function tableSortJs(test = false, domDocumentWindow = document) {
   function checkIfTesting() {
	   console.log("checkif testing madhe ahe mi");
     if (test === true) {
       const getTagTable = domDocumentWindow.getElementsByTagName("table");
       const createTableHead = domDocumentWindow.createElement("thead");
       return [getTagTable, createTableHead];
     } else {
       const getTagTable = document.getElementsByTagName("table");
       const createTableHead = document.createElement("thead");
       return [getTagTable, createTableHead];
     }
   }

  const [getTagTable, createTableHead] = checkIfTesting();
  const columnIndexAndTableRow = {};
  //const fileSizeColumnTextAndRow = {};
  for (let table of getTagTable) {
    if (table.classList.contains("table-sort")) {
		//console.log("calling maketable", table);
      makeTableSortable(table);
    }
  }

  function makeTableSortable(sortableTable) {
    
    const tableHead = sortableTable.querySelector("thead");
    const tableBody = sortableTable.querySelector("tbody");
    const tableHeadHeaders = tableHead.querySelectorAll("th");
    tableHead.style.cursor = "pointer";
	
    let columnIndexesClicked = [];
    for (let [columnIndex, th] of tableHeadHeaders.entries()) {
      let timesClickedColumn = 0;

      th.addEventListener("click", function () {
        const tableRows = tableBody.querySelectorAll("tr");
        const columnData = [];
        let isDataAttribute = th.classList.contains("data-sort");

        let isDayOfWeek = th.classList.contains("days-of-week");

        // Handle filesize sorting (e.g KB, MB, GB, TB) - Turns data into KiB.
        let isFileSize = th.classList.contains("file-size");

        let isRememberSort = sortableTable.classList.contains("remember-sort");
        // Checking if user has clicked different column from the first column if yes reset times clicked.
        if (!isRememberSort) {
			console.log("remember sorting");
          columnIndexesClicked.push(columnIndex);
          if (timesClickedColumn === 1 && columnIndexesClicked.length > 1) {
            const lastColumnClicked =
              columnIndexesClicked[columnIndexesClicked.length - 1];
            const secondLastColumnClicked =
              columnIndexesClicked[columnIndexesClicked.length - 2];
            if (lastColumnClicked !== secondLastColumnClicked) {
              timesClickedColumn = 0;
              columnIndexesClicked.shift();
            }
          }
        }

        timesClickedColumn += 1;

        getTableData();
        updateTable();

        function updateTable() {
          for (let [i, tr] of tableRows.entries()) {
            
			 if (!isFileSize) {
              tr.innerHTML = columnIndexAndTableRow[columnData[i]];
            }
          }
        }

        function getTableData() {
          for (let [i, tr] of tableRows.entries()) {
            // inner text for column we click on
            let tdTextContent = tr.querySelectorAll("td").item(columnIndex)
              .textContent;
            if (tdTextContent.length === 0) {
              tdTextContent = "";
            }
            if (tdTextContent.trim() !== "") {
              if (!isFileSize && !isDayOfWeek && !isDataAttribute) {
                columnData.push(`${tdTextContent}#${i}`);
                columnIndexAndTableRow[`${tdTextContent}#${i}`] = tr.innerHTML;
              }
            } else {
              // Fill in blank table cells dict key with filler value.
              columnData.push(`!X!Y!Z!#${i}`);
              columnIndexAndTableRow[`!X!Y!Z!#${i}`] = tr.innerHTML;
            }
          }

          function naturalSortAescending(a, b) {
            if (a.includes("X!Y!Z!#")) {
              return 1;
            } else if (b.includes("X!Y!Z!#")) {
              return -1;
            } else {
              return a.localeCompare(
                b,
                navigator.languages[0] || navigator.language,
                { numeric: true, ignorePunctuation: true }
              );
            }
          }

          function naturalSortDescending(a, b) {
            return naturalSortAescending(b, a);
          }

          function clearArrows(arrowUp = " ▲", arrowDown = " ▼") {
			tempVal = th.innerText;
			tempVal = tempVal.replace(/[\u25BC]/g,"");
			tempVal = tempVal.replace(/[\u25B2]/g,"")
			$(th).html(tempVal);
			}

          let arrowUp = " &#9650";
          let arrowDown = " &#9660";
		  console.log(arrowUp, arrowDown);
          // Sort naturally; default aescending unless th contains 'order-by-desc' as className.
          if (columnData[0] === undefined) {
            return;
          }
	
          let desc = th.classList.contains("order-by-desc");
          let tableArrows = sortableTable.classList.contains("table-arrows");

          if (timesClickedColumn === 1) {
            if (desc) {
              if (tableArrows) {
                clearArrows(arrowUp, arrowDown);
				var text =$(th).html();
				
				text = text+arrowDown;
				$(th).html(text); 
              }
              columnData.sort(naturalSortDescending, {
                numeric: true,
                ignorePunctuation: true,
              });
            } else {
              if (tableArrows) {
				  clearArrows(arrowUp, arrowDown);
				var text =$(th).html();
				
				text = text+arrowUp;
				$(th).html(text); 
              }
              columnData.sort(naturalSortAescending);
            }
          } else if (timesClickedColumn === 2) {
            timesClickedColumn = 0;
            if (desc) {
              if (tableArrows) {
                clearArrows(arrowUp, arrowDown);
				var text =$(th).html();
				
				text = text+arrowUp;
				$(th).html(text); 
              }
              columnData.sort(naturalSortAescending, {
                numeric: true,
                ignorePunctuation: true,
              });
            } else {
              if (tableArrows) {
                clearArrows(arrowUp, arrowDown);
				var text =$(th).html();
				
				text = text+arrowDown;
				$(th).html(text); 
              }
              columnData.sort(naturalSortDescending);
            }
          }
        }
      });
    }
  }
}

if (
  document.readyState === "complete" ||
  document.readyState === "interactive"
) {
  tableSortJs();
} else if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", tableSortJs, false);
}
if (typeof module == "object") {
  module.exports = tableSortJs;
}
