import type { key_val } from '$lib/stores/ae_stores';
import { get_object } from './api_get_object';

// The lookup "obj_type" should broken out into a separate function. - 2024-08-07
// Updated 2023-11-15
export async function get_ae_obj_li_for_obj_id_crud({
    api_cfg,
    obj_type,
    for_obj_type,
    for_obj_id, // NOTE: Changed 2023-12-06 to no longer required
    use_alt_table = false,
    use_alt_base = false,
    // inc = {},
    enabled = 'enabled',
    hidden = 'not_hidden',
    order_by_li = null,
    limit = 999999,
    offset = 0,
    // key,
    // jwt = null,
    headers = {},
    params_json = null, // NOTE: This is a JSON object that needs to be safely converted to a string for the params. This is used for the API endpoint. Example: { "fulltext_search": { "default_qry_str": "Search string for default", "address_default_qry_str": "Search string for address", "contact_1_default_qry_str": "Search string for contact_1" } }
    // json_obj = null, // NOTE: This is a JSON object that needs to be safely converted to a string for the params. This is used for the search endpoint.
    params = {},
    return_meta = false,
    log_lvl = 0
}: {
    api_cfg: any;
    obj_type: string;
    for_obj_type: null | string;
    for_obj_id?: string;
    use_alt_table?: boolean;
    use_alt_base?: boolean;
    // inc?: key_val
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    order_by_li?: any;
    limit?: number;
    offset?: number;
    // key: string,
    // jwt?: string,
    headers?: any;
    params_json?: any;
    // json_obj?: any,
    params?: key_val;
    return_meta?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** get_ae_obj_li_for_obj_id_crud() *** [${obj_type}]`);
    }

    // data = {};
    // data['super_key'] = key;
    // data['jwt'] = jwt;
    // NOTE: The key and or JWT should be in the header of the DELETE, GET, PATCH, POST

    // const endpoint = `/crud/${obj_type}/list`;

    let endpoint = '';
    if (obj_type == 'account') {
        endpoint = `/crud/account/list`;
    } else if (obj_type == 'address') {
        endpoint = `/crud/address/list`;
    } else if (obj_type == 'archive') {
        endpoint = `/crud/archive/list`;
    } else if (obj_type == 'archive_content') {
        endpoint = `/crud/archive/content/list`;
    } else if (obj_type == 'contact') {
        endpoint = `/crud/contact/list`;
    } else if (obj_type == 'data_store') {
        endpoint = `/crud/data_store/list`;
    } else if (obj_type == 'event') {
        endpoint = `/crud/event/list`;
    } else if (obj_type == 'event_abstract') {
        endpoint = `/crud/event/abstract/list`;
    } else if (obj_type == 'event_badge') {
        endpoint = `/crud/event/badge/list`;
    } else if (obj_type == 'event_device') {
        endpoint = `/crud/event/device/list`;
    } else if (obj_type == 'event_exhibit') {
        endpoint = `/crud/event/exhibit/list`;
    } else if (obj_type == 'event_exhibit_tracking') {
        endpoint = `/crud/event/exhibit/tracking/list`;
    } else if (obj_type == 'event_file') {
        endpoint = `/crud/event/file/list`;
    } else if (obj_type == 'event_location') {
        endpoint = `/crud/event/location/list`;
    } else if (obj_type == 'event_person') {
        endpoint = `/crud/event/person/list`;
    } else if (obj_type == 'event_presentation') {
        endpoint = `/crud/event/presentation/list`;
    } else if (obj_type == 'event_presenter') {
        endpoint = `/crud/event/presenter/list`;
    } else if (obj_type == 'event_session') {
        endpoint = `/crud/event/session/list`;
    } else if (obj_type == 'event_track') {
        endpoint = `/crud/event/track/list`;
    } else if (obj_type == 'grant') {
        endpoint = `/crud/grant/list`;
    } else if (obj_type == 'hosted_file') {
        endpoint = `/crud/hosted_file/list`;
    } else if (obj_type == 'journal') {
        endpoint = `/crud/journal/list`;
    } else if (obj_type == 'journal_entry') {
        endpoint = `/crud/journal/entry/list`;
    } else if (obj_type == 'order') {
        endpoint = `/crud/order/list`;
    } else if (obj_type == 'order_line') {
        endpoint = `/crud/order/line/list`;
    } else if (obj_type == 'page') {
        endpoint = `/crud/page/list`;
    } else if (obj_type == 'person') {
        endpoint = `/crud/person/list`;
    } else if (obj_type == 'post') {
        endpoint = `/crud/post/list`;
    } else if (obj_type == 'post_comment') {
        endpoint = `/crud/post/comment/list`;
    } else if (obj_type == 'site') {
        endpoint = `/crud/site/list`;
    } else if (obj_type == 'sponsorship_cfg') {
        endpoint = `/crud/sponsorship/cfg/list`;
    } else if (obj_type == 'sponsorship') {
        endpoint = `/crud/sponsorship/list`;
        // } else if (obj_type == 'user') {
        //     endpoint = `/crud/user/list`;
    } else if (obj_type == 'lu' && for_obj_type == 'country_subdivision') {
        endpoint = `/crud/lu/country_subdivision/list`;
        for_obj_type = null;
    } else if (obj_type == 'lu' && for_obj_type == 'country') {
        endpoint = `/crud/lu/country/list`;
        for_obj_type = null;
    } else if (obj_type == 'lu' && for_obj_type == 'time_zone') {
        endpoint = `/crud/lu/time_zone/list`;
        for_obj_type = null;
    } else {
        console.log(`Unknown object type: ${obj_type}`);
        return false;
    }
    if (log_lvl) {
        console.log('Endpoint:', endpoint);
    }

    if (for_obj_type) {
        params['for_obj_type'] = for_obj_type;
    }
    if (for_obj_id) {
        params['for_obj_id'] = for_obj_id;
    }

    params['use_alt_table'] = use_alt_table;
    params['use_alt_base'] = use_alt_base;

    /* Need to deal with inc params here */

    const allowed_enabled_list = ['all', 'enabled', 'not_enabled'];
    if (allowed_enabled_list.includes(enabled)) {
        params['enabled'] = enabled;
    }

    const allowed_hidden_list = ['all', 'hidden', 'not_hidden'];
    if (allowed_hidden_list.includes(hidden)) {
        params['hidden'] = hidden;
    }

    // NOTE: The order_by_li variable is in the "headers" because if is a the URL GET params do not handle multiple values very well. Maybe base64 encore in the future or something? Reminder that GET requests should not have a body (no JSON).
    // NOTE: The order_by_li should be a key value pair of the property/DB field to sort and how to sort (ASC or DESC)
    if (order_by_li) {
        if (log_lvl) {
            console.log('Order By:', order_by_li);
        }
        headers['order_by_li'] = order_by_li;
    }

    if (limit >= 0) {
        params['limit'] = limit;
    }

    if (offset >= 0) {
        params['offset'] = offset;
    }

    if (params_json) {
        // NOTE: This is a JSON object that needs to be safely converted to a string for the params. This is used for the search endpoint.
        // Max characters for a GET request is 2083. This is a limitation of the browser (Microsoft IE and Edge).
        if (log_lvl) {
            console.log('JSON Object:', params_json);
            console.log(JSON.stringify(params_json));
        }
        // NOTE: "jp" stands for "JSON Params"
        params['jp'] = encodeURIComponent(JSON.stringify(params_json));
        if (params['jp'].length > 2083) {
            console.log(
                `The JSON object is too large to be used as a GET parameter. The overall max URL length is 2083 characters. Please use the POST endpoint instead. Length = ${params['jp'].length} [THIS DOES NOT EXIST YET]`
            );
            return false;
        }
    }

    // if (json_obj) {
    //     // NOTE: This is a JSON object that needs to be safely converted to a string for the params. This is used for the search endpoint.
    //     // Max characters for a GET request is 2083. This is a limitation of the browser (Microsoft IE and Edge).
    //     console.log('JSON Object:', json_obj);
    //     params['json_str'] = encodeURIComponent(JSON.stringify(json_obj));
    //     if (params['json_str'].length > 2083) {
    //         console.log(`The JSON object is too large to be used as a GET parameter. The overall max URL length is 2083 characters. Please use the POST endpoint instead. Length = ${params['json_str'].length} [THIS DOES NOT EXIST YET]`);
    //         return false;
    //     }
    // }

    if (log_lvl) {
        console.log('Params:', params);
    }

    const object_li_get_promise = await get_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        headers: headers,
        params: params,
        return_meta: return_meta,
        log_lvl: log_lvl
    });

    if (log_lvl > 1) {
        console.log(object_li_get_promise);
    }

    return object_li_get_promise;
}
