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");


const statsTable = document.querySelector("#stats");
const statsHeader = document.querySelector("#stats thead");
const statsBody = document.querySelector("#stats tbody");

const overviewHeader = document.querySelector("#overview thead");
const overviewBody = document.querySelector("#overview tbody");

const watchButton = document.querySelector("#watch");
const showStatsButton = document.querySelector("#showStats");

//const watchlist = await postData("/getWatchlist", {}, token);

populatePlayerData();
updateIsWatched();

watchButton.onclick = async e => {
    e.preventDefault();

    const id = window.location.pathname.split("/")[2].replace("#", "");
    const resultObject = await postData("/toggleWatched", { id: id }, token);
    //alert(resultObject.message);
    updateIsWatched();
}

showStatsButton.onclick = async e => {
    e.preventDefault();

    statsTable.style.display = statsTable.style.display == "" ? "none" : "";
    showStatsButton.innerHTML = statsTable.style.display == "" ? "Hide Full Stats" : "Show Full Stats";
}

async function updateIsWatched() {
    const id = window.location.pathname.split("/")[2].replace("#", "");
    const resultObject = await postData("/isWatched", {id: id}, token);
    const isWatched = resultObject.isWatched;
    watchButton.innerHTML = isWatched ? "Stop Watching Player" : "Watch Player";
}

async function populatePlayerData() {
    const id = window.location.pathname.split("/")[2].replace("#", "");
    let resultObject = await postData("/getPlayerStats", {
        playerID: id
    }, token);
    if (resultObject.success === false) {
        console.log("Invalid ID");
        return;
    }

    const playerStatsObject = resultObject.matches;

    
    let playerObjectResult = await postData("/getPlayerScores", {
        playerID: id
    }, token);
    if (playerObjectResult.success === false) {
        console.log("Invalid ID");
        return;
    }

    const playerObject = playerObjectResult.match;
    console.log(playerObjectResult);

    for (const [attribute, value] of Object.entries(playerObject)) {
        console.log(`.attribute-${attribute}`);
        document.querySelectorAll(`.attribute-${attribute}`).forEach(element => {
            if (element.classList.contains("format-weight")) {
                element.textContent = value + " lbs";
                return;
            }
            if (element.classList.contains("format-height")) {
                element.textContent = `${value.split("-")[0]}' ${value.split("-")[1]}"`;
                return;
            }
            if (element.classList.contains("format-integer")) {
                element.textContent = Math.floor(value);
                return;
            }
            if (element.classList.contains("format-salary")) {
                element.textContent = formatSalary(value);
                return;
            }
            element.textContent = value;
        })
    };
    
    createStatsTable(playerStatsObject);
    createOverviewTable(playerObject);
}

async function createOverviewTable(playerObject) {
    const tableHeader = overviewHeader;
    const tableBody = overviewBody;

    nomatch.style.display = "none"
    tableHeader.innerHTML = "";
    const headerRow = document.createElement("tr")
    //Object.keys(resultObject.matches[0]).forEach(attribute => {
    //   headerRow.innerHTML += `<td>${attribute}</td>`; 
    //});pass_attempts, complete_pass, total_yards, total_tds, interception, receptions, receiving_yards, receiving_touchdown, rush_attempts, rushing_yards, rush_touchdown, fumble
    headerRow.innerHTML += `
            <td>Contract</td>
            <td>APY</td>
            <td>Years</td>
            <td>Duration</td>
            `;
    tableHeader.appendChild(headerRow);

    tableBody.innerHTML = "";
    const row = playerObject;
    const rowElement = document.createElement("tr");

    //for (attribute in player) {
    //    row.innerHTML += `<td>${player}</td>l`;
    //}
    rowElement.innerHTML = `
        <td>${formatSalary(row.TrueAvgPerYear * row.Years)}</td>
        <td>${formatSalary(row.TrueAvgPerYear)}</td>
        <td>${row.Years}</td>
        <td>${row.StartYear}-${row.EndYear}</td>
    `;
    tableBody.appendChild(rowElement);
}

async function createStatsTable(playerObject) {
    const tableHeader = statsHeader;
    const tableBody = statsBody;

    nomatch.style.display = "none"
    tableHeader.innerHTML = "";
    const headerRow = document.createElement("tr")
    //Object.keys(resultObject.matches[0]).forEach(attribute => {
    //   headerRow.innerHTML += `<td>${attribute}</td>`; 
    //});pass_attempts, complete_pass, total_yards, total_tds, interception, receptions, receiving_yards, receiving_touchdown, rush_attempts, rushing_yards, rush_touchdown, fumble
    headerRow.innerHTML += `
            <td>Season</td>
            <td>Season Type</td>
            <td>Week</td>
            <td>Pass Attempts</td>
            <td>Complete Passes</td>
            <td>Total Yards</td>
            <td>Total Touchdowns</td>
            <td>Interceptions</td>
            <td>Receptions</td>
            <td>Recieving Yards</td>
            <td>Receiving Touchdowns</td>
            <td>Rush Attempts</td>
            <td>Rushing Yards</td>
            <td>Rushing Touchdowns</td>
            <td>Fumbles</td>
            `;
    tableHeader.appendChild(headerRow);

    tableBody.innerHTML = "";
    playerObject.forEach(row => {
        const rowElement = document.createElement("tr");

        //for (attribute in player) {
        //    row.innerHTML += `<td>${player}</td>l`;
        //}
        console.log(row)
        rowElement.innerHTML = `
            <td>${row.season}</td>
            <td>${row.seasontype == "REG" ? "Regular" : "Post"}</td>
            <td>${row.week}</td>
            <td>${row.pass_attempts}</td>
            <td>${row.complete_pass}</td>
            <td>${row.total_yards}</td>
            <td>${row.total_tds}</td>
            <td>${row.interception}</td>
            <td>${row.receptions}</td>
            <td>${row.receiving_yards}</td>
            <td>${row.receiving_touchdown}</td>
            <td>${row.rush_attempts}</td>
            <td>${row.rushing_yards}</td>
            <td>${row.rush_touchdown}</td>
            <td>${row.fumble}</td>
        `;
        tableBody.appendChild(rowElement);
    });
}
    //});pass_attempts, complete_pass, total_yards, total_tds, interception, receptions, receiving_yards, receiving_touchdown, rush_attempts, rushing_yards, rush_touchdown, fumble