<script setup lang="ts">
import { ref} from 'vue';

const props = defineProps(
    {
        headersObject : Object
    } 
)

const emit = defineEmits([
    'update:httpHeaders'
])

const headerData  = ref(props.headersObject)
const newHeaderName = ref('');
const newHeaderValue = ref('');

function setAddButtonStyle() {
    return isNewHeaderEmpty() ? "inactive-button" : "tool-button";
}

function isNewHeaderEmpty() {
    return newHeaderName.value.trim().length == 0;
}

function isHeaderEssential(headerName : string){
    return headerName == "Keep-Alive" || headerName == "Connection" || headerName == "Date"
}

function setEssentialHeaderStyle(headerName : string){
    return isHeaderEssential(headerName) ? "inactive-button" : "tool-button";
}

function deleteHeader(index : string){
    if(!isHeaderEssential(index) && headerData.value != undefined){
        delete headerData.value[index]
        emit('update:httpHeaders',headerData.value)
    }
}

function addNewHeader(name : string, value : string){
    if (headerData.value == undefined)
        return;

    if (isNewHeaderEmpty()) return;

    headerData.value[name] = value;
    newHeaderName.value = "";
    newHeaderValue.value = "";
    emit('update:httpHeaders',headerData.value);
}

</script>

<template>
    
    <div class="flex flex-col gap-4">
        <label>Response Headers</label>
        <div class="flex flex-row gap-4">
            <div class="w-full">Header name</div>
            <div class="w-full">Header value</div>
            <div class="w-52 px-4"></div>
        </div>  
        <div class="flex flex-row gap-4" v-for="(item, index) in headerData" :key="index">
            <input type="text" :value="index" class="text-field" disabled/>
            <input type="text" :value="item" class="text-field" disabled/>
            <button @click="deleteHeader(index)" class="w-56" :class="setEssentialHeaderStyle(index)">Remove</button>
        </div>
        <div class="flex flex-row gap-4">
            <input type="text" v-model="newHeaderName" @change="() => setAddButtonStyle()" class="text-field"  />
            <input type="text" v-model="newHeaderValue" class="text-field"  />
            <button @click="addNewHeader(newHeaderName, newHeaderValue)" :class="setAddButtonStyle()" class="w-56">Add</button>
        </div>
    </div>
</template>