<template>
    <ScrollComponent ref="scrollComponent" v-show="logs">
        <div class="console" v-if="logs">
            <p class="log no-wrap" v-for="(log, index) in logs" :class="{ even: index % 2, wrap: config.lineWrap, nowrap: !config.lineWrap }"><span v-if="config.podNames">{{ log.podName }}</span><span v-if="config.timestamps">[{{ dayjs(log.timestamp).format('YYYY-MM-DD HH:mm') }}]</span><span v-html="process(log.message)"></span></p>
        </div>
    </ScrollComponent>
    <div v-if="logs == null" class="center" style="height: 100%; width: 100%">
        <UiLoadingIcon size="2rem"></UiLoadingIcon>
    </div>
</template>

<script setup lang="ts">
import type {Log} from "~/requests/logs";
import dayjs from "dayjs";
import type {ConsoleConfig} from "~/components/inspect/logs/ConsoleConfig";

const props = defineProps<{
    config: ConsoleConfig
    logs?: Log[]
}>()

const scrollComponent = ref();

onMounted(() => {
    watch(props, () => {
        scrollComponent.value.scrollToBottom();
    }, { immediate: true, deep: true })
})

function process(text: string)
{
    return text.replace(/https?:\/\/\S+/g, (url) => {
        return StringUtils.format("<a class='external' href='%s' target='_blank'>%s</a>", url, url);
    })
    .replace("INFO", () => {
        return StringUtils.format("<span class='marked green'>%s</span>", "INFO");
    })
    .replace("[INFO]", () => {
        return StringUtils.format("<span class='marked green'>%s</span>", "[INFO]");
    })
    .replace("WARN", () => {
        return StringUtils.format("<span class='marked yellow'>%s</span>", "WARN");
    })
    .replace("[WARN]", () => {
        return StringUtils.format("<span class='marked yellow'>%s</span>", "[WARN]");
    })
    .replace("ERROR", () => {
        return StringUtils.format("<span class='marked red'>%s</span>", "ERROR");
    })
    .replace("[ERROR]", () => {
        return StringUtils.format("<span class='marked red'>%s</span>", "[ERROR]");
    });
}
</script>

<style scoped>
.log {
    display: grid;
    grid-template-columns: auto auto 1fr;
    padding: 0.125rem 1rem;
    gap: 1rem;
}
.log *:not(a, .marked) {
    width: 100%;
    max-width: 100%;
    color: white;
    line-height: 1.15rem;
    padding: 0.1rem 0;
    font-weight: 600;
    font-size: 0.95rem;
}

.console {
    background-color: #0e0e0e;
    border-radius: 0.5rem;
    display: grid;
    padding: 1rem 0;
    align-content: start;
}
.even {
    background-color: rgb(35, 35, 35);
}

.wrap {
    word-break: break-all;
    white-space: pre-wrap;
}

.nowrap *:not(a) {
    white-space: pre;
}
.green {
    color: #2e9a00;
}
</style>