const searchesTable = document.querySelector('#searches-table').getElementsByTagName('tbody')[0];;
const searchRowTemp = document.querySelector('#search-row-temp');
const contentContainer = document.querySelector('.content-container');


async function loadSearches() {
    let loaadingAnimation = startLoadingAnimation();
    let res = await api.GET('/getAllSearchResults.php',true);
    endLoadingAnimation(loaadingAnimation);
    if(!res.success) {
        showPopup('Fehler',res.msg);
        return false;
    }

    let i = 1;
    for(let search of res.data)
    {
        let createdDate = new Date(search.created);
        let createdStr = createdDate.toLocaleDateString();
        let row = searchRowTemp.content.cloneNode(true).querySelector('tr');
        row.querySelector('.id').textContent = i;
        row.querySelector('.location').textContent = search.location.name;
        row.querySelector('.type').textContent = search.type;
        row.querySelector('.radius').textContent = search.radius+'km';
        row.querySelector('.min-rooms').textContent = search.minRooms?search.minRooms:'-';
        row.querySelector('.max-rooms').textContent = search.maxRooms?search.maxRooms:'-';
        row.querySelector('.min-price').textContent = formatedPrice(search.minPrice);
        row.querySelector('.max-price').textContent = formatedPrice(search.maxPrice);
        row.querySelector('.total-querys-executed').textContent = search.results.length;
        // row.querySelector('.created').textContent = createdStr;
        for(let td of row.querySelectorAll('td')) {
            if(td.textContent == '-') {
                td.classList.add('center');
            }
        }
        row.addEventListener('click', (e) => {
            localStorage.setItem('selected-search',JSON.stringify(search));
            window.location = '../view-search/view-search.html';
        })
        searchesTable.appendChild(row);
        i++;
    }
}
loadSearches();

function formatedPrice(price) {
    if(!price) {
        return '-';
    }
    if(price > 1000) {
        return `${(price/1000)}K`;
    }
    if(price > 1000000) {
        return `${(price/1000000)}M`;
    }
    
    return price+'€';
}