<template>
    <PopupTemplate :heading="'Logs: ' + deployment.metadata.namespace + '/' + deployment.metadata.name" ref="base" @close="emits('close')">
        <div class="log-container" v-if="pods">
            <div class="spaced-center">
                <div class="left-center">
                    <UiButton @click="() => config.timestamps = true" v-if="!config.timestamps"><span>Show Timestamp</span> <UiIcon>visibility</UiIcon></UiButton>
                    <UiButton @click="() => config.timestamps = false" v-if="config.timestamps"><span>Hide Timestamp</span> <UiIcon>visibility_off</UiIcon></UiButton>
                    <UiButton @click="() => config.podNames = true" v-if="!config.podNames"><span>Show Pod Name</span> <UiIcon>visibility</UiIcon></UiButton>
                    <UiButton @click="() => config.podNames = false" v-if="config.podNames"><span>Hide Pod Name</span> <UiIcon>visibility_off</UiIcon></UiButton>
                    <UiButton @click="() => config.lineWrap = true" v-if="!config.lineWrap"><span>Wrap Line</span> <UiIcon>format_text_wrap</UiIcon></UiButton>
                    <UiButton @click="() => config.lineWrap = false" v-if="config.lineWrap"><span>Unwrap Line</span> <UiIcon>format_text_overflow</UiIcon></UiButton>
                </div>
            </div>
            <Console :logs="logs" :config="config"></Console>
        </div>
    </PopupTemplate>
</template>

<script setup lang="ts">
import { LogRepo } from '~/classes/LogRepo';
import { Pod } from '~/classes/Pod';
import { Log } from '~/requests/logs';
import Console from "~/components/inspect/logs/Console.vue";
import type {Deployment} from "~/classes/Deployment";
import UiIcon from "~/components/ui/UiIcon.vue";
import { ConsoleConfig } from '~/components/inspect/logs/ConsoleConfig'

const config = ref(ConsoleConfig.default(true, true, false));

const base = ref();

const logs: Ref<Log[]> = ref([]);
const pods: Ref<Pod[] | undefined> = ref(undefined);

const props = defineProps<{
    deployment: Deployment
}>();

const emits = defineEmits<{
    (e: 'close'): void
}>()

const logRepo = new LogRepo();
onMounted(() => {
    logRepo.listen("deployments", props.deployment.metadata.namespace, props.deployment.metadata.name,(_logs: Log[]) => {
        logs.value.push(..._logs);
    });
    Pod.getByDeployment(props.deployment.metadata.namespace, props.deployment.metadata.name, (_pods: Pod[]) => {
        pods.value = _pods;
    });
});
onUnmounted(() => {
    logRepo.clear();
});

onMounted(() => {
    document.addEventListener('keydown', (event) => {
        if(event.key === 'Escape') 
        {
            emits('close');
        }
    });
})
</script>

<style scoped>
.log-container {
    height: 100%;
    display: grid;
    grid-template-rows: auto 1fr;
    gap: 0.5rem;
}
</style>