var userID;
window.onload = async () => 
{
    const fragment = new URLSearchParams(window.location.hash.slice(1));
    const [accessToken, tokenType] = [fragment.get('access_token'), fragment.get('token_type')];
    var guilds;
    const avatar = document.getElementById('avatar');
    const userName = document.getElementById('userName');
    var table = document.getElementById('guilds')

    if (!accessToken) return window.location.href = '/';
    fetch('https://discord.com/api/users/@me', 
    {
        headers: {
            authorization: `${tokenType} ${accessToken}`,
        },
    })
    .then(result => result.json())
    .then(response => 
    {
        userID = response.id;
        avatar.style.backgroundImage = `url(https://cdn.discordapp.com/avatars/${response.id}/${response.avatar}.jpeg)`
        userName.textContent = response.username
    })
    .catch(console.error);
    fetch('https://discord.com/api/users/@me/guilds', 
    {
        headers: {
            authorization: `${tokenType} ${accessToken}`,
        },
    })
    .then(result => result.json())
    .then(response => 
    {
        guilds = response.filter(x=>x.owner==true);
        for(var guild of guilds)
        {
            (async (guild)=>
            {
                var row = document.createElement('tr');
                var name = document.createElement('td');
                name.textContent = guild.name;
                var settings = document.createElement('td');
                settings.id = guild.id;
                var gear = document.createElement('span');
                gear.classList.add('material-symbols-outlined')
                gear.onclick = handleSettigns
                gear.textContent = 'settings';
                row.appendChild(name);
                var addRemData = document.createElement('td');
                if(!await hasRem(guild.id)) 
                {
                    var button = document.createElement('div');
                    button.classList.add('DiscordAddBtn');
                    addRemData.appendChild(button);
                }
                row.appendChild(addRemData);
                settings.appendChild(gear);
                row.appendChild(settings);
                table.appendChild(row)
            })(guild)
        }

    })
    .catch(console.error);

};

function handleSettigns(event)
{
    var guildID = event.target.parentNode.id;
    var guildName = event.target.parentNode.parentNode.childNodes[0].textContent;
    var popup = document.getElementById('popup');
    const data = {guildID}
    fetch(`${window.location.origin}/api/getGuildData`, 
    {
        method: "POST",
        mode: "cors", 
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(result => result.json())
    .then(res => 
    {
        popup.classList.remove('hidden');
        popup.children[1].textContent = guildName;
        popup.children[1].id = guildID;
        let music = document.getElementById('music')
        music.textContent = res.music? 'check_box' :'check_box_outline_blank';
        let strikes = document.getElementById('strikes')
        strikes.textContent = res.strikes? 'check_box' :'check_box_outline_blank';
        music.onclick = requestChange;
        strikes.onclick = requestChange;
        
        
    })
    .catch(console.error);
}
async function hasRem(guildID)
{
    return await fetch(`${window.location.origin}/api/hasRem`, 
    {
        method: "POST",
        mode: "cors", 
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({guildID}), // body data type must match "Content-Type" header
    })
    .then(result => result.json())
    .then(res => 
    {
        return res.hasRem;
    })
    .catch(console.error);
}

function handleClose(element)
{
    element.parentNode.classList.add('hidden');
}
async function requestChange()
{
    
    return await fetch(`${window.location.origin}/api/change`, 
    {
        method: "POST",
        mode: "cors", 
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({guildID:event.target.parentNode.parentNode.children[1].id,userID, property:event.target.id}), // body data type must match "Content-Type" header
    })
    .then(result => result.json())
    .then(res => 
    {
        if(!res.error)
        {
            let music = document.getElementById('music')
            music.textContent = res.music? 'check_box' :'check_box_outline_blank';
            let strikes = document.getElementById('strikes')
            strikes.textContent = res.strikes? 'check_box' :'check_box_outline_blank';
        }
    })
    .catch(console.error);
}