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

// *** Import Aether core variables and functions
import type { key_val } from '$lib/ae_stores';
// import { api, Element_obj_tbl_row } from 'aether_npm_lib';
import Element_obj_tbl_row from '$lib/element_obj_tbl_row.svelte';
import { post_object } from '$lib/ae_api/api_post_object';

// *** Import Aether core components
// import Element_obj_tbl_row from './element_obj_tbl_row.svelte';

// *** Import Aether module variables and functions

// *** Import Aether module components

// *** Export/Exposed variables and functions for component
export let api_cfg: any;
export let show_textarea = true;
export let button_label = 'Run SQL!';
export let show_record_count = true;
export let remove_breaks = false;
export let run_on_load = false;

export let sql_statement: string;
export let sql_data = null;
export let as_list = false;
export let log_lvl: number = 0;

// *** Set initial variables
let ae_promises: key_val = {};
let sql_qry_result: any = 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, data, 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"
        on:click={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 border-primary-500"
        >
        {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 table-compact table-bordered table-striped  min-w-min sql_qry_result text-xs">
                    <Element_obj_tbl_row row_header={true} obj={sql_qry_result[0]} primary_obj_li_type='' />
                    {#each sql_qry_result as record}
                        <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>
