<script lang="ts">
import {afterUpdate} from 'svelte';
export let data: Array<any> | undefined = undefined;
export let nofooter: boolean = false;
export let noheader: boolean = false;
export let omit: string[] = ['id'];
export let title: string | undefined = undefined;

function getDataKeys(data: any[]): string[] {
    if (!data || data.length === 0) return [];
    return Object.keys(data[0]).map(k => k.split('_').join(' ')).filter(k => !omit.includes(k));
}

function getRow(row: Record<string, any>): Array<any> {
   return Object.entries(row).filter(r => !omit.includes(r[0]));
}

const formatter = new Intl.DateTimeFormat('en', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
    timeZone: "America/New_York"
});

function formatDatum([key, value]: any[]) {
    if (key === 'date') {
        const parsedDate = new Date(value);
        return formatter.format(parsedDate);
    }

    if (key === 'user') {
        return value['name'];
    }

    return value;
}

</script>
<table>
    {#if title}
    <h2>{title}</h2>
    {/if}
    {#if !noheader}
    <thead>
        <tr>
            {#each getDataKeys(data) as header}
                <th>{header}</th>
            {/each}
        </tr>
    </thead>
    {/if}
    <tbody>
        {#if data}
        {#each data as row}
        <tr>
            {#each getRow(row) as datum}
            
            <td>{formatDatum(datum)}</td>
            {/each}
        </tr>
        {/each}
        {:else}
        <tr>
            There is not data.
        </tr>   
        {/if}
    </tbody>
    {#if !nofooter}
    <slot name="footer">
       <tfoot>
        <tr>
            <td>Table Footer</td>
        </tr>
       </tfoot>
    </slot>
    {/if}
</table>
<style>
table {
    padding: 16px;
    margin: 8px;
    border: solid 1px black;
    border-collapse: collapse;
}

th {
    text-transform: capitalize;
}

thead tr {
    background: rgba(0,0,23, 0.34);
}

tbody tr:nth-child(odd) {
   background: rgba(0,0,23,0.14); 
}

th, td {
    padding: 1em;
    border: 1px solid rgba(0,0,0, 1);
}
</style>
