const loactionInput = document.querySelector('#location');
const searchBtn = document.querySelector('#search');
const resultsContainer = document.querySelector('#results');
let fetchedLocations = [];
let fetchedLocationIds = [];
let fetchTimeout = null;

searchBtn.addEventListener('click', (e) => {
    fetchLocationsFromInput();
})

async function handleInput() {
    if(fetchTimeout) {
        clearTimeout(fetchTimeout)
    }
    fetchTimeout = setTimeout(() => {
        fetchLocationsFromInput();
    },800,true);
}

async function fetchLocationsFromInput() {

    let res = await getLocation(loactionInput.value);
    resultsContainer.innerHTML = '';
    for(let location of res.locations) {
        if(!fetchedLocationIds.includes(location.id))
        {
            fetchedLocations.push(location);
            fetchedLocationIds.push(location.id);
        }
        
        let locationEl = document.createElement('div');
        locationEl.classList.add('location-el');
        locationEl.textContent = location.name;

        locationEl.addEventListener('click',async (e) => {
            let res = await api.POST('uploadLocation.php',{
                locations: fetchedLocations
            },true);
            if(!res.success) {
                showPopup('Fehler',res.msg);
                return;
            }
            localStorage.setItem('selected-location',JSON.stringify(location));
            window.location = '../create-search/create-search.html'
        });

        resultsContainer.appendChild(locationEl);
    }
    
}


loactionInput.addEventListener('input',handleInput)

async function getLocation(location)
{
    if(!location) {
        return {locations: []};
    }
    let res = await fetch(`https://www.desk.immo/locations/${location}`, {
        "credentials": "include",
        "headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0",
            "Accept": "*/*",
            "Accept-Language": "de,en-US;q=0.7,en;q=0.3",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With": "XMLHttpRequest",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            // "Cookie": "XSRF-TOKEN=eyJpdiI6IlVBU2xSS1RPNFFjODBJNmNRZ3J1L3c9PSIsInZhbHVlIjoiYjM4eVF3ajEzODJISWxQN1A1Q1IzMHA2b1RJWDNMTTZnVlRqd0ZQdHNNQVg1emFxbWtocURqaVB4T0VyNlNZcDBseWs5YjhVSWVIazJidHFjTEY2eUkyZTBVMTkxd2t4SkVNdE1PRkNNV1RvQnZ5SUJ0MmxJVjROSW5BaUFlOVQiLCJtYWMiOiJjMzZjNTBkZTA0MTNlMDA1YzYxYmU1NThmOWMxZmE4N2M1YmZjZmM2ZTcwZGZhYjA3ZmRhZmEyZmQxZGRmZjJlIn0%3D; deskimmo_session=eyJpdiI6ImltT3h4YlVZQXVLOWFKbThUNjEyVkE9PSIsInZhbHVlIjoiQ1FoUy9IUml3dTlydkowZHRySkxYS0pZVmdiQmpxZFBhVnY0bitnSXhHam1lczdEbWFsbDJpNFdFUWVqL3BoLzk3VEFvRGpXbDlDNXpYV0U1cFEzd1NzT3BtcE9jYUkvWkNIWFBHd2NYRmkvMmxyQVVEWkFyQW5wNG5SMlRFSU0iLCJtYWMiOiI0NzU1ZjdkYWViZmFhNGE5NGI4NWQ4MzAzZjU0ZjNkMzJlYTY5MDNjNzZmMDFlZmRhNzk0ZjZkYTkzZjU3Y2EyIn0%3D; visid_incap_2897561=fid5DOLOT7quTGJFDeA2/1iTpmQAAAAAQUIPAAAAAADlX3g7HEy/eSA40Y7rEDD2; incap_ses_108_2897561=W1Z3AlImp3nxL1HYC7J/AViTpmQAAAAA+tnr7aVZfBLbKVPCRflAwQ==; _pk_id.18.01d6=b5f6c1bae3757384.1688638299.; _pk_ses.18.01d6=1; _gcl_au=1.1.699986535.1688638299"
        },
        "referrer": "https://www.desk.immo/search/public",
        "method": "GET",
        "mode": "cors"
    });
    if(res.status < 200 ||res.status >= 300)
    {
        return {locations: []};
    }

    let text = await res.text();
    try {
        let json = JSON.parse(text);
        return json;
    }
    catch {
        return {locations: []};
    }
}