const socket = io()
const checkBox = document.getElementById('check-scroll-checkbox')
const messages = document.getElementById('messages-box-list')
const chatForm = document.getElementById('chat-box-form')
const chatInput = document.getElementById('chat-box-input')
const checkBoxConsole = document.getElementById('check-scroll-console-checkbox')
const consoleMessages = document.getElementById('console-messages-box-list')
const consoleForm = document.getElementById('console-box-form')
const consoleInput = document.getElementById('console-box-input')
const statsData = document.getElementById('stats-data')
const botInfo = document.getElementById('bot-info')
const main = document.getElementById('main')
const header = document.getElementById('header')

function secureSend(type, data) {
    const password = localStorage.getItem('password')
    if (password == null) return
    socket.emit('jsondat', JSON.stringify({type, data, password}))
}

socket.on('message', (data) => {
    updateMessages(data)
})

socket.on('consoleViewer', (data) => {
    secureSend('consoleAdd', {msg: data})
    updateConsoleMessages(data)
})

socket.on('stats', (data) => {
    console.log(`Received new data with estimate profit of: ${data.estimate}`)
    updateStats(data)
})

function updateBotInfo(data) {
    botInfo.innerHTML = `
    <h2>BinMaster</h2>
    <h3>IGN: ${data?.ign ?? 'Failed to retrieve username'}</h3>
    <a href="https://mc-heads.net" target="_blank">
      <img src="${data?.img ?? 'Failed to retrieve image source'}" />
    </a>
  `
}

function updateStats(data) {
    statsData.innerHTML = `
    <h2>Stats</h2>
    Purse balance: ${intToString(data.purse)} coins
    <br>
    Purse after sold: ${intToString(data.auctionValue)} coins
    <br>
    Estimated profit: ${intToString(data.estimate)} coins
    <br>
    Active auctions: ${data.activeAuctions}
    <br>
    State: ${data.state.toUpperCase()}
  `
}

function updateMessages(data) {
    const el = document.createElement('div')
    el.innerHTML = data
    el.classList.add('msg')
    messages.appendChild(el)
    updatePageScroll()
}

function updateConsoleMessages(data) {
    const el = document.createElement('div')
    el.innerHTML = data
    el.classList.add('msg')
    consoleMessages.appendChild(el)
    updatePageScroll()
}

function updatePageScroll() {
    if (checkBox.checked) {
        messages.scrollTop = messages.scrollHeight
    }

    if (checkBoxConsole.checked) {
        consoleMessages.scrollTop = consoleMessages.scrollHeight
    }
}

function intToString(num) {
    if (num > 999 && num < 1000000) {
        return (num / 1000).toFixed(1) + 'K'
    } else if (num > 1000000000) {
        return (num / 1000000000).toFixed(1) + 'B'
    } else if (num > 1000000) {
        return (num / 1000000).toFixed(1) + 'M'
    } else if (num < 900) {
        return num
    }
}

async function getConfig() {
    return JSON.parse(await (await fetch('/config', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({password: localStorage.getItem('password')})
    })).text())
}

window.onload = async () => {
    main.style.top = `${header.clientHeight}px`
    const response = await getConfig()
    updateBotInfo(response.server.botInfo)
    updateAuctions(response.server.stats.activeIDs)
    updateStats(response.server.stats)

    for (const msg of response.server.messages) {
        updateMessages(msg)
        updatePageScroll()
    }

    for (const consoleMsg of response.server.consoleMessages) {
        updateConsoleMessages(consoleMsg)
    }
}

window.onresize = () => {
    main.style.top = `${header.clientHeight}px`
}

chatForm.onsubmit = (ev) => {
    ev.preventDefault()
    if (chatInput.value === '' || chatInput.value == null) return
    console.log(`New chat input: ${chatInput.value}`)
    secureSend('msg', {msg: chatInput.value})
    chatInput.value = ''
}

consoleForm.onsubmit = (ev) => {
    ev.preventDefault()
    if (consoleInput.value === '' || chatInput.value == null) return
    console.log(`New console input: ${consoleInput.value}`)
    secureSend('consoleMsg', {msg: consoleInput.value})
    consoleInput.value = ''
}
