<script lang="ts">
import { onMount } from 'svelte';

// *** Import Aether related
import type { key_val } from '$lib/stores/ae_stores';
import Element_obj_tbl_row from '$lib/elements/element_obj_tbl_row.svelte';
import { post_object } from '$lib/ae_api/api_post_object';

interface Props {
    // *** Export/Exposed variables and functions for component
    api_cfg: any;
    show_textarea?: boolean;
    button_label?: string;
    show_record_count?: boolean;
    remove_breaks?: boolean;
    run_on_load?: boolean;
    sql_statement: string;
    sql_data?: any;
    as_list?: boolean;
    log_lvl?: number;
}

let {
    api_cfg,
    show_textarea = true,
    button_label = 'Run SQL!',
    show_record_count = true,
    remove_breaks = false,
    run_on_load = false,
    sql_statement = $bindable(),
    sql_data = null,
    as_list = false,
    log_lvl = 0
}: Props = $props();

// *** Set initial variables
let ae_promises: key_val = $state({});
let sql_qry_result: any = $state(null);

onMount(() => {
    console.log('** Element Mounted: ** Element SQL Query');

    if (run_on_load) {
        console.log('Run On Load');
        let result = handle_run_sql(
            sql_statement,
            sql_data,
            as_list,
            log_lvl
        ).then((qry_result) => {
            console.log('SQL Query Result:', qry_result);
            sql_qry_result = qry_result;
            return qry_result;
        });
    }
});

// const dispatch = createEventDispatcher();

async function handle_run_sql(
    qry: string,
    data: any,
    as_list = false,
    log_lvl = 0
) {
    console.log('*** handle_run_sql() ***');

    let sql_qry_data: key_val = {};

    let endpoint = '/sql/select';
    let params: key_val = {};
    if (as_list) {
        params['as_list'] = true;
    }
    if (log_lvl) {
        console.log('Params:', params);
    }

    if (qry) {
    } else {
        return false;
    }
    if (log_lvl > 1) {
        console.log('Qry:', qry);
    }

    if (remove_breaks) {
        sql_qry_data['sql_qry'] = qry.replace(/(\r\n|\n|\r)/gm, '');
    } else {
        sql_qry_data['sql_qry'] = qry;
    }

    sql_qry_data['sql_data'] = data;

    if (log_lvl) {
        console.log('SQL Qry Data:', sql_qry_data);
    }

    ae_promises.sql_qry_promise = await post_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: sql_qry_data,
        log_lvl: log_lvl
    });

    if (log_lvl) {
        console.log('SQL Query Results', ae_promises.sql_qry_promise);
    }

    return ae_promises.sql_qry_promise;
}
</script>

<section id="sql_qry" class="sql_qry">
    {#if show_textarea}
        <textarea class="textarea" bind:value={sql_statement}></textarea>
    {/if}

    <div class="text-center">
        <button
            type="button"
            onclick={async () => {
                sql_qry_result = await handle_run_sql(
                    sql_statement,
                    sql_data,
                    as_list,
                    log_lvl
                );
            }}
            class="btn btn-md preset-tonal-primary hover:preset-tonal-primary border-primary-500 border">
            {button_label}
        </button>
    </div>

    {#if show_record_count && sql_qry_result && sql_qry_result.length}
        <div>
            Record count: <strong>{sql_qry_result.length}</strong>
        </div>
    {/if}

    <div class="sql_statement_result">
        {#await ae_promises.sql_qry_promise}
            Getting results...
        {:then}
            {#if sql_qry_result && sql_qry_result.length}
                <table
                    class="table-compact table-bordered table-striped sql_qry_result table min-w-min text-xs">
                    <Element_obj_tbl_row
                        row_header={true}
                        obj={sql_qry_result[0]}
                        primary_obj_li_type="" />
                    {#each sql_qry_result as record, index (index)}
                        <Element_obj_tbl_row
                            obj={record}
                            primary_obj_li_type="" />
                    {/each}
                </table>
            {:else}
                <div>Nothing to show yet...</div>
            {/if}
        {/await}
    </div>
</section>

<style lang="postcss">
/* .sql_qry textarea {
    width: 100%;
    height: 8em;
} */
</style>
