import type { key_val } from '$lib/ae_stores';
import { api } from '$lib/api';

// import { liveQuery } from "dexie";
import { db_events } from "$lib/db_events";

// let event_badge_li = liveQuery(
//     () => db_events.badges.toArray()
// );

let ae_promises: key_val = {}; // Promise<any>;

async function handle_load_ae_obj_id__event({api_cfg, event_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__event() *** event_id=${event_id}`);

    let params = {};

	// $events_sess.badges.status_load__event_obj = 'loading';
    ae_promises.load__event_obj = await api.get_ae_obj_id_crud({
        api_cfg: api_cfg,
        obj_type: 'event',
        obj_id: event_id, // NOTE: This is the FQDN, not normally the ID.
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (event_obj_get_result) {
        if (event_obj_get_result) {
            return event_obj_get_result;
        } else {
            console.log('No results returned.');
            return null;
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_promises.load__event_obj;
}




// Updated 2024-03-06
async function handle_load_ae_obj_li__badge({api_cfg, event_id, try_cache=true}) {
    console.log(`*** handle_load_ae_obj_li__badge() *** event_id=${event_id}`);

    let fulltext_search_qry_str = ''; // $events_sess.badges.fulltext_search_qry_str;

    let enabled = 'enabled'; // $events_loc.qry_enabled;
    let hidden = 'not_hidden'; // $events_loc.qry__hidden;
    let limit = 25; // $events_loc.qry__limit;
    let offset = 0; // $events_loc.qry__offset;

    // if ($ae_loc.administrator_access) {
    //     enabled = 'all';
    //     hidden = 'all';
    //     limit = 500;
    // } else if ($ae_loc.trusted_access) {
    //     // enabled = 'all';
    //     hidden = 'all';
    //     limit = 50;
    // }

    let params = {};

    let params_json: key_val = {};
    if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
        params_json['ft_qry'] = {
            'default_qry_str': fulltext_search_qry_str,
            // 'location_address_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
            // 'contact_li_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
            };
    }

    // console.log('params_json:', params_json);
    // console.log(params_json);

    // $events_sess.badges.status_qry__search = 'loading';
    ae_promises.load__event_badge_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: api_cfg,
        obj_type: 'event_badge',
        for_obj_type: 'event',
        for_obj_id: event_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        enabled: enabled,
        hidden: hidden,
        order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'updated_on': 'DESC', 'created_on': 'DESC'},
        // order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 2
        })

    .then(function (badge_obj_li_get_result) {
        // console.log('Badge list:', badge_obj_li_get_result);
        if (badge_obj_li_get_result) {
            // $slct.badge_obj_li = badge_obj_li_get_result;
            handle_db_save_ae_obj_li__badge({obj_type: 'event_badge', obj_li: badge_obj_li_get_result});
            return badge_obj_li_get_result;
        } else {
            // $slct.badge_obj_li = [];
            return [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        // $events_sess.badges.status_qry__search = 'done';

        // console.log('Badge list:', badge_obj_li_get_result);
        // return badge_obj_li_get_result;
    });

    console.log('ae_promises.load__event_badge_obj_li:', ae_promises.load__event_badge_obj_li);
    return ae_promises.load__event_badge_obj_li;
}


async function handle_load_ae_obj_id__exhibit({api_cfg, exhibit_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__exhibit() *** exhibit_id=${exhibit_id}`);

    let params = {};

    // $events_sess.exhibits.status_load__exhibit_obj = 'loading';
    ae_promises.load__exhibit_obj = await api.get_ae_obj_id_crud({
        api_cfg: api_cfg,
        obj_type: 'event_exhibit',
        obj_id: exhibit_id, // NOTE: This is the FQDN, not normally the ID.
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (exhibit_obj_get_result) {
        if (exhibit_obj_get_result) {
            // This is expecting a list
            handle_db_save_ae_obj_li__exhibitor({obj_type: 'event_exhibit', obj_li: [exhibit_obj_get_result]});
            return exhibit_obj_get_result;
        } else {
            console.log('No results returned.');
            return null;
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_promises.load__exhibit_obj;
}


// Updated 2024-03-06
async function handle_load_ae_obj_li__exhibit({api_cfg, event_id, try_cache=true}) {
    console.log(`*** handle_load_ae_obj_li__exhibit() *** event_id=${event_id}`);

    let enabled = 'enabled'; // $events_loc.qry_enabled;
    let hidden = 'not_hidden'; // $events_loc.qry__hidden;
    let limit = 50; // $events_loc.qry__limit;
    let offset = 0; // $events_loc.qry__offset;

    // if ($ae_loc.administrator_access) {
    //     enabled = 'all';
    //     hidden = 'all';
    //     limit = 500;
    // } else if ($ae_loc.trusted_access) {
    //     // enabled = 'all';
    //     hidden = 'all';
    //     limit = 50;
    // }

    let params = {};

    let params_json: key_val = {};
    // params_json['and_qry'] = {};
    // params_json['and_qry']['license_max'] = 10;

    params_json['and_in_li'] = {
        license_max : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    };

    // if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
    //     params_json['ft_qry'] = {
    //         'default_qry_str': fulltext_search_qry_str,
    //         // 'location_address_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
    //         // 'contact_li_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
    //         };
    // }

    // console.log('params_json:', params_json);
    // console.log(params_json);

    // $events_sess.exhibits.status_qry__search = 'loading';
    ae_promises.load__event_exhibit_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: api_cfg,
        obj_type: 'event_exhibit',
        for_obj_type: 'event',
        for_obj_id: event_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        enabled: enabled,
        hidden: hidden,
        order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'updated_on': 'DESC', 'created_on': 'DESC'},
        // order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 2
        })

    .then(function (exhibit_obj_li_get_result) {
        // console.log('Badge list:', exhibit_obj_li_get_result);
        if (exhibit_obj_li_get_result) {
            // $slct.exhibit_obj_li = exhibit_obj_li_get_result;
            handle_db_save_ae_obj_li__exhibitor({obj_type: 'event_exhibit', obj_li: exhibit_obj_li_get_result});
            return exhibit_obj_li_get_result;
        } else {
            // $slct.exhibit_obj_li = [];
            return [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        // $events_sess.exhibits.status_qry__search = 'done';

        // console.log('Badge list:', exhibit_obj_li_get_result);
        // return exhibit_obj_li_get_result;
    });

    console.log('ae_promises.load__event_exhibit_obj_li:', ae_promises.load__event_exhibit_obj_li);
    return ae_promises.load__event_exhibit_obj_li;
}


// // This function will loop through the badge_obj_li and save each one to the DB.
// function handle_db_save_ae_obj_li({obj_type, obj_li}) {
//     console.log(`*** handle_db_save_ae_obj_li() ***`);

//     if (obj_li && obj_li.length) {
//         obj_li.forEach(async function (obj) {
//             // console.log(`ae_obj ${obj_type}:`, obj);

//             try {
//                 const id_random = await db_events.badges.put({
//                     id_random: obj.event_badge_id_random,
//                     full_name: obj.full_name,
//                     full_name_override: obj.full_name_override,
//                     email: obj.email,
//                     email_override: obj.email_override,
//                     affiliations: obj.affiliations,
//                     affiliations_override: obj.affiliations_override,
//                     badge_type: obj.badge_type,
//                     badge_type_override: obj.badge_type_override,
//                     badge_type_code: obj.badge_type_code,
//                     badge_type_code_override: obj.badge_type_code_override,
//                     external_event_id: obj.external_event_id,
//                     external_id: obj.external_id,
//                     external_person_id: obj.external_person_id,
//                     created_on: obj.created_on,
//                     updated_on: obj.updated_on,
//                 });
//                 console.log(`Put obj with ID: ${obj.event_badge_id_random} or ${id_random}`);
//             } catch (error) {
//                 let status = `Failed to put ${obj.event_badge_id_random}: ${error}`;
//                 console.log(status);
//             }

//             // const id_random = await db_events.badges.put(obj);
//             // console.log(`Put obj with ID: ${obj.event_badge_id_random}`);
//         });

//         return true;
//     }
// }


// This function will loop through the badge_obj_li and save each one to the DB.
function handle_db_save_ae_obj_li__badge({obj_type, obj_li}) {
    console.log(`*** handle_db_save_ae_obj_li__badge() ***`);

    if (obj_li && obj_li.length) {
        obj_li.forEach(async function (obj) {
            // console.log(`ae_obj ${obj_type}:`, obj);

            try {
                const id_random = await db_events.badges.put({
                    id_random: obj.event_badge_id_random,
                    full_name: obj.full_name,
                    full_name_override: obj.full_name_override,
                    email: obj.email,
                    email_override: obj.email_override,
                    affiliations: obj.affiliations,
                    affiliations_override: obj.affiliations_override,
                    badge_type: obj.badge_type,
                    badge_type_override: obj.badge_type_override,
                    badge_type_code: obj.badge_type_code,
                    badge_type_code_override: obj.badge_type_code_override,
                    external_event_id: obj.external_event_id,
                    external_id: obj.external_id,
                    external_person_id: obj.external_person_id,
                    created_on: obj.created_on,
                    updated_on: obj.updated_on,
                });
                console.log(`Put obj with ID: ${obj.event_badge_id_random} or ${id_random}`);
            } catch (error) {
                let status = `Failed to put ${obj.event_badge_id_random}: ${error}`;
                console.log(status);
            }

            // const id_random = await db_events.badges.put(obj);
            // console.log(`Put obj with ID: ${obj.event_badge_id_random}`);
        });

        return true;
    }
}

// This function will loop through the event_exhibit_obj_li and save each one to the DB.
function handle_db_save_ae_obj_li__exhibitor({obj_type, obj_li}) {
    console.log(`*** handle_db_save_ae_obj_li__exhibitor() ***`);

    if (obj_li && obj_li.length) {
        obj_li.forEach(async function (obj) {
            // console.log(`ae_obj ${obj_type}:`, obj);

            try {
                const id_random = await db_events.exhibits.put({
                    id_random: obj.event_exhibit_id_random,
                    code: obj.code,
                    name: obj.name,
                    description: obj.description,
                    staff_passcode: obj.staff_passcode,
                    data_json: obj.data_json,
                    license_max: obj.license_max,
                    license_li_json: obj.license_li_json,
                    cfg_json: obj.cfg_json,
                    created_on: obj.created_on,
                    updated_on: obj.updated_on,
                });
                console.log(`Put obj with ID: ${obj.event_exhibit_id_random} or ${id_random}`);
            } catch (error) {
                let status = `Failed to put ${obj.event_exhibit_id_random}: ${error}`;
                console.log(status);
            }

            // const id_random = await db_events.exhibits.put(obj);
            // console.log(`Put obj with ID: ${obj.event_exhibit_id_random}`);
        });

        return true;
    }
}




let export_obj = {
    handle_load_ae_obj_id__event: handle_load_ae_obj_id__event,
    handle_load_ae_obj_li__badge: handle_load_ae_obj_li__badge,
    handle_load_ae_obj_id__exhibit: handle_load_ae_obj_id__exhibit,
    handle_load_ae_obj_li__exhibit: handle_load_ae_obj_li__exhibit,
};
export let events_func = export_obj;
