<template>
    <div class="content-l">
        <h2>Env</h2>
        <ContainerPicker :containers="pod.spec.containers" v-if="pod.spec.containers.length > 0" @selected="payload => container = payload"></ContainerPicker>
        <UiInput v-if="error === false">
            <input type="text" name="" id="" v-model="filter" placeholder="Filter...">
        </UiInput>
        <ScrollComponent>
            <div>
                <div class="env" v-for="env in filteredEnv" v-if="error === false">
                    <UiMask class="spaced-center" :prefix="env.key" :enabled="isSensitive(env.key)" :value="env.value"></UiMask>
                </div>
                <div v-if="error === true">
                    <UiPompt :prompt="new Prompt('This pod does not support retrieving environment variables using \'env\'', PromptType.ERROR)"></UiPompt>
                </div>
            </div>
        </ScrollComponent>
    </div>
</template>

<script setup lang="ts">
import type { Container, Pod } from '~/classes/Pod';
import { EnvVar } from '../env/EnvVar';
import ContainerPicker from '~/components/ui/ContainerPicker.vue';
import UiMask from '~/components/ui/UiMask.vue';
import { Prompt, PromptType } from '~/components/ui/Prompt';
import UiPompt from '~/components/ui/UiPompt.vue';

const props = defineProps<{
    pod: Pod
}>();

const container: Ref<Container | undefined> = ref(undefined);
const error = ref(false);

const envs: Ref<EnvVar[] | undefined> = ref(undefined);
watch(container, (container) => {
    if (container && container.name)
    {
        EnvVar.get(props.pod.metadata.namespace, props.pod.metadata.name, container.name, (_envs: EnvVar[]) => {
            error.value = false;
            envs.value = _envs;
        }, () => {
            error.value = true;
        });
    }
}, { immediate: true });

const filter = ref("");
const filteredEnv = computed(() => {
    if (envs.value)
    {
        return envs.value.filter(item => item.key.toLowerCase().includes(filter.value.toLowerCase()));
    }
});

function isSensitive(key: string)
{
    const markers = ["token", "key", "password", "secret", "private", "credential", "auth", "jwt"];
    for (const marker of markers)
    {
        if (key.toLowerCase().includes(marker) && !key.toLowerCase().includes("public"))
        {
            return true;
        }
    }
    return false;
}
</script>

<style scoped>
.env {
    background-color: var(--shade-light);
    padding: 0.25rem 0.5rem;
}
.env.env:nth-of-type(2n) {
    background-color: var(--shade-dark);
}
.env:hover {
    background-color: #cecece;
}
.env {
    display: grid;
    grid-template-columns: auto 1fr;
}
</style>
