const PROXY_URL = "http://" + "KAFKA_REST_HOST"
const TOPIC = "great.ideas"
const CONSUMERS = PROXY_URL + "/consumers"

function addIdea(idea) {
    document.getElementById("list").innerHTML +=
        "<li>" + idea + "</li>"
}

async function doForever(f) {
    await f()
    return setTimeout(async function() {
        await f()
        return doForever(f)
    }, 3000)
}

function processRecord(record) {
    let value = record.value
    let out = ""
    out += value.verb + " "
    out += value.adjective + " "
    out += value.noun + " "
    addIdea(out)
}

async function start() {
    let c = await makeConsoomer()
    doForever(async function() {
        consoom(c)
    })
}

async function post(url, data) {
    return fetch(url, {
        method: 'POST',
        cache: "no-cache",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/vnd.kafka.v2+json",
            "Accept": "application/vnd.kafka.v2+json",
            "Sec-Fetch-Site": "cross-site"
        }
    })
}

async function get(url) {
    let resp = await fetch(url, {
        method: 'GET',
        cache: "no-cache",
        headers: {
            "Accept": "application/vnd.kafka.json.v2+json",
            "Sec-Fetch-Site": "cross-site"
        }
    })
    return resp
}

async function subscribe(c) {
    return post(c + "/subscription", {
        topics: [TOPIC]
    })
}

async function makeConsoomer() {
    let uuid = newUuid()
    let config = {
        name: uuid,
        format: "json",
        "auto.offset.reset": "latest",
    }
    let response = await post(CONSUMERS + "/" + uuid, config)
    let body = await response.json()
    let c = body.base_uri
    await subscribe(c)
    return c
}

async function consoom(c) {
    let resp = await get(c + "/records")
    let records = await resp.json()
    records.forEach(processRecord)
}

// dirty hack since we don't have crypto available outside of a secure context
function newUuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
