import("/_content/IMaskJsWrapper/imask.min.js");

const dictionary = new Map();

export function mask(id, mask, isRegEx, definitions, toUpperCase, dotnetHelper) {
    let pattern;
    if (isRegEx)
        pattern = new RegExp(mask);
    else
        pattern = mask;
    const options = {
        mask: pattern,
        commit: function (value, masked) {
            dotnetHelper.invokeMethodAsync('MaskCommit', {Value: value, UnMaskedValue: this.unmaskedValue});
        }
    };

    if (toUpperCase)
        options.prepareChar = str => str.toUpperCase();

    if (definitions) {
        const defsObj = JSON.parse(definitions);
        options.definitions = Object.fromEntries(Object.entries(defsObj).map(([key, value]) => [`${key}`, new RegExp(value)]));
    }

    const maskControl = IMask(document.getElementById(id), options);
    dictionary.set(id, maskControl);
}

export function updateValue(id, value) {
    const maskControl = dictionary.get(id);
    maskControl.updateValue(value);
}