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

const emit = defineEmits([
    'click:showHeaders',
    'click:showBody',
])

interface historyRecord {
    clientUUID : String,
    dateTimeStamp: String,
    headers : Headers ,
    httpMethod: String,
    requestBody: String
}

interface Headers {
    'content-type': String,
    [propName: string]: any;
}

const clientUUID = localStorage.getItem("clientUUID")
const fetchLink = window.location.protocol + "//" + window.location.hostname + "/mock/api/event";
const historyRecords : Ref<Array<historyRecord>> = ref([]);


fetch(fetchLink+"/"+clientUUID).then(response => response.json()).then(data => { historyRecords.value = data });

function parseTimeStamp(timestamp : String){
    return timestamp.substring(10,19).replace("T"," ");
}

function showHeaders(headers: Object, index : number){
    emit('click:showHeaders',headers, index)
}

function showBody(body: String , index : number, contentType: String){

    emit('click:showBody',body, index, contentType  )
}

function refreshHistory(){
    fetch(fetchLink+"/"+clientUUID).then(response => response.json()).then(data => { historyRecords.value = data });
}

</script>

<template>
    <div class="h-28 text-center text-grey-900 dark:text-white">
        <table class="w-full">
            <tr>
                <th>Time</th>
                <th>Request <br>HTTP Method</th>
                <th>Request Headers</th>
                <th>Request Body</th>
                <th class="text-2xl"><button @click="refreshHistory()">⟳</button></th>
            </tr>
            <tr v-for="(item , index) in historyRecords" :key="index">
                <td> {{ parseTimeStamp(item.dateTimeStamp) }} </td>
                <td> {{ item.httpMethod }} </td>
                <td> <button @click="showHeaders(item.headers, index)" class="underline">Show Headers</button> </td>
                <td> 
                    <button v-if="item.requestBody.length != 0" @click="showBody(item.requestBody, index, item.headers['content-type'])" class="underline">Show Body</button> 
                    <span v-else>Empty</span>
                </td>
            </tr>
        </table>
    </div>
</template>