/*!
 * Copyright (c) what3words http://what3words.com
 */
import { ScriptInitParameter, ScriptInitParameters, SELECTORS, } from "./constants";
/**
 * Reference: https://www.totaltypescript.com/iterate-over-object-keys-in-typescript#solution-2-type-predicates
 */
export function isKey(x, k) {
    return k in x;
}
/**
 * Converts a string of coordinate pair values into an array of coordinate objects
 * @param coordinatesString A string of coordinate pair values e.g. `67.234,-42.00,24.24,47.42`
 */
export const convertToCoordinates = (coordinatesString) => {
    var _a, _b;
    const coordinatesArr = coordinatesString.split(",");
    const result = [];
    for (let i = 0; i < coordinatesArr.length; i += 2) {
        result.push(parseCoordinates((_a = coordinatesArr[i]) !== null && _a !== void 0 ? _a : "", (_b = coordinatesArr[i + 1]) !== null && _b !== void 0 ? _b : ""));
    }
    return result;
};
/**
 * Parses coordinate string and returns as an object with floating values
 * @param lat A coordinate-like string
 * @param lng A coordinate-like string
 * @returns object
 */
export const parseCoordinates = (lat, lng) => ({
    lat: parseFloat(lat),
    lng: parseFloat(lng),
});
/**
 * Validates if a value or array is empty
 * @param input the value or array to validate if empty
 */
export const isEmpty = (input) => {
    return input === null || input === undefined || input.length === 0;
};
/**
 * Retrieves API options that are settable via query parameters in the request of the SDK. This function retrieves and
 * returns an object with all found parameters if any exist
 * @returns object
 */
export function getScriptInitOptions() {
    const options = {};
    const scriptTag = document.querySelector(SELECTORS.script);
    if (scriptTag) {
        const url = new URL(scriptTag.src);
        const params = new URLSearchParams(url.search);
        params.forEach((value, key) => {
            if (ScriptInitParameters.includes(key)) {
                switch (key) {
                    case ScriptInitParameter.KEY:
                    case ScriptInitParameter.BASEURL:
                    case ScriptInitParameter.CALLBACK:
                        options[key] = value;
                        break;
                    case ScriptInitParameter.HEADERS:
                        if (value.length > 0)
                            options[key] = JSON.parse(value);
                }
            }
        });
    }
    return options;
}
