import { postData, verifyLogin } from "./client.js";
import { formatSalary } from "./utils.js";

const searchForm = document.getElementById("searchForm");

const token = window.localStorage.getItem("token");

const tableHeader = document.getElementById("header");
const tableBody = document.getElementById("results");
const table = document.getElementById("table");
const nomatch = document.getElementById("nomatch");

updateTableVisibility();

document.querySelectorAll("input[type='checkbox']").forEach(checkbox => {
    checkbox.addEventListener("change", e => {
        e.preventDefault();
        updateSearch();
    });
});

document.querySelectorAll("input[type='text']").forEach(checkbox => {
    checkbox.addEventListener("input", e => {
        e.preventDefault();
        updateSearch();
    });
});

if (searchForm)searchForm.onsubmit = e => {
    e.preventDefault();
    updateSearch();
};

updateSearch();
    
async function updateSearch () {
    if (!verifyLogin()) return;

    const formData = new FormData(searchForm);
    
    let positions = formData.getAll("days");

    while (positions.length !== 4) {
        positions.push("NOPE");
    }
    
    let resultObject = await postData("/getPlayers", {
        player: document.getElementById("query").value || "%",
        positions: positions
    }, token);

    if (resultObject.matches.length === 0) {
       nomatch.style.display = "";
       table.style.display = "none";
       return;
    }
    nomatch.style.display = "none"
    table.style.display = "";
    tableHeader.innerHTML = "";
    const headerRow = document.createElement("tr")
    //Object.keys(resultObject.matches[0]).forEach(attribute => {
    //   headerRow.innerHTML += `<td>${attribute}</td>`; 
    //});
    headerRow.innerHTML += `
            <td>ID</td>
            <td>Name</td>
            <td>Contract</td>
            <td>Team</td>
            <td>Position</td>
            `;
    tableHeader.appendChild(headerRow);

    tableBody.innerHTML = "";
    resultObject.matches.forEach(player => {
        const row = document.createElement("tr");

        //for (attribute in player) {
        //    row.innerHTML += `<td>${player}</td>l`;
        //}
        row.innerHTML = `
            <td>${player.PlayerID}</td>
            <td><a href="/player/${player.PlayerID}">${player.PlayerName}</a></td>
            <td>${formatSalary(player.TotalValue)}</td>
            <td>${player.Team}</td>
            <td>${player.Position}</td>
        `;
        tableBody.appendChild(row);
    });
    updateTableVisibility();
};

function updateTableVisibility() {
    if (!tableBody) return;

    const rows = tableBody.querySelectorAll("tr");
    if (rows == null) return;
    if (rows.length != 0) {
        table.style.display = "";
    } else {
        table.style.display = "none";
    }
}
