import { getSidebarCustomize } from "./getSidebarCustomize.js";

const CUSTOMIZE_CLASS_CHECKBOX = "customize-control customize-control-checkbox";

/**
 * Get the sanitized value from a customizer control (e.g. `"1"` of a checkbox gets converted to `boolean`).
 */
function getSanitizedControlValue(controlId: string, defaultValue?: any) {
    const customize = getSidebarCustomize();

    // Check sanitization
    let sanitize: "checkbox";
    const controlContainer = customize.control(controlId)?.container as JQuery<HTMLLIElement>;

    if (!controlContainer) {
        // Control not found
        return null;
    }

    if (controlContainer.hasClass(CUSTOMIZE_CLASS_CHECKBOX) || typeof defaultValue === "boolean") {
        sanitize = "checkbox";
    }

    // Check if value generally changed
    let currentValue = customize(controlId).get();

    // Do some common sanitization
    if (sanitize === "checkbox") {
        currentValue = !!+currentValue;
    } else if (!isNaN(+currentValue)) {
        currentValue = +currentValue;
    }

    return currentValue;
}

export { getSanitizedControlValue, CUSTOMIZE_CLASS_CHECKBOX };
