utils.js

import { LAYOUTS, POSITIONS, MIME_TYPES } from "./constants";

/**
 * @ignore
 */
const hasValue = (obj, v) => {
    const values = Object.values(obj);
    return values.includes(v);
};

/**
 * @ignore
 */
const getKey = (obj, value) => {
    return Object.entries(obj).find(([key, val]) => val === value)?.[0];
};

/**
 * @ignore
 */
const validateLayoutSettings = (layoutSettings) => {
    const { targetElement, layout, position, width, height } = layoutSettings;
    if (!targetElement instanceof HTMLElement) {
        console.error('The targetElement is not instance of HTMLElement.');
    }
    if (layout !== undefined && !hasValue(LAYOUTS, layout)) {
        console.error(`The leyout type - ${this.layout} doesn't exists in the supported layouts list.`);
    }

    if (position !== undefined && !hasValue(POSITIONS, position)) {
        console.error(`The position ${this.position} doesn't exists in the supported positions list.`);
    }

    if (width !== undefined && typeof width !== 'number') {
        console.error(`The width value should be number type.`);
    }

    if (height !== undefined && typeof height !== 'number') {
        console.error(`The height value should be number type.`);
    }

    if (layout === LAYOUTS.CUSTOM_SIZE && (width === undefined || height === undefined)) {
        console.error(`The width and height values are required for LAYOUTS.CUSTOM_SIZE layout type .`);
    }
};

/**
 * @ignore
 */
const validateDataType = (data) => {
    const expectedTypes = {
        uploadPhoto: 'boolean',
        showCatalog: 'boolean',
        showBackToWebsiteButton: 'boolean',
        userId: 'string',
        catalogFilter: 'string',
        locale: 'string',
        context: 'string',

        openInRoom: 'string',
        openWithProduct: 'string',
        openWithCollection: 'string',
    };

    Object.entries(expectedTypes).forEach(([key, type]) => {
        const value = data[key];
        if (value !== undefined && typeof value !== type) {
            console.error(`The ${key} must be ${type}.`);
        }
    });
};

/**
 * @ignore
 */
const isValidUrl = (urlString) =>{
    var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
        '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    return !!urlPattern.test(urlString);
};

/**
 * @ignore
 */
const isBase64 = (str) => {
    return str.substr(0, 10) === 'data:image';
};

/**
 * Formats a base64-encoded string as a complete image source URL for use in HTML image tags.
 * 
 * @function
 * @memberof WizartDeploymentKit
 * @param {string} base64 - The base64-encoded image data.
 * @param {MimeTipe} [mimeType=MIME_TYPES.IMAGE_PNG] - The MIME type of the image (e.g., "image/png" or "image/jpeg"). 
 * Defaults to PNG if not specified.
 * @returns {string} A formatted data URL combining the specified MIME type and base64 image data, ready for use as a `src` attribute in image elements.
 * 
 * @example
 * const imageUrl = formatBase64ImageSrc("iVBORw0KGgoAAAANSUhEUgAA...", WizartDeploymentKit.MIME_TYPE.IMAGE_PNG);
 * // Returns: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
 */
const formatBase64ImageSrc = (base64, mimeType = MIME_TYPES.IMAGE_PNG) => {
    return `data:${mimeType};base64,${base64}`;
};

export {
    hasValue,
    getKey,
    validateLayoutSettings,
    validateDataType,
    isValidUrl,
    isBase64,
    formatBase64ImageSrc
}