"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCustomCssList = exports.newReplaceAll = exports.objPropStr2AST = exports.key2ObjCall = exports.objValueStr2AST = exports.getSiblingPaths = exports.parseName = exports.isOriginTagOrNativeComp = exports.getReactiveValue = exports.isOnlySpaceContent = exports.isMustacheReactive = exports.isInlineStatementFn = exports.camelize = exports.trimCurly = exports.getRandomStr = void 0;
const t = require("@babel/types");
const getRandomStr = () => {
    let res = '';
    const str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    for (let i = 0; i < 10; i += 1) {
        res += str.charAt(Math.floor(Math.random() * str.length));
    }
    return res;
};
exports.getRandomStr = getRandomStr;
const trimCurly = str => str.replace(/(?:{{)|(?:}})/gi, '');
exports.trimCurly = trimCurly;
// 驼峰化单词
const camelize = str => {
    return str.replace(/[-_\s]+(.)/g, (match, key) => {
        return key ? key.toUpperCase() : '';
    });
};
exports.camelize = camelize;
const isInlineStatementFn = statament => {
    const reg = /\(([\s\S]*?)\)/;
    return statament.match(reg);
};
exports.isInlineStatementFn = isInlineStatementFn;
const isMustacheReactive = value => {
    const reg = /(?=.*[{]{2})(?=.*[}]{2})/;
    return reg.test(value);
};
exports.isMustacheReactive = isMustacheReactive;
const isOnlySpaceContent = value => {
    const reg = /[^\s]+/;
    return !reg.test(value);
};
exports.isOnlySpaceContent = isOnlySpaceContent;
const getReactiveValue = nodeValue => {
    let newNodeValue = nodeValue;
    const vLength = newNodeValue && newNodeValue.length;
    const newValue = [];
    if (newNodeValue && (0, exports.isMustacheReactive)(newNodeValue)) {
        for (let idx = 0; idx < vLength; idx += 1) {
            if (newNodeValue[idx] === '{' &&
                idx < vLength - 1 &&
                newNodeValue[idx + 1] === '{') {
                newValue.push("'+(");
                idx += 1;
            }
            else if (newNodeValue[idx] === '}' &&
                idx < vLength - 1 &&
                newNodeValue[idx + 1] === '}') {
                newValue.push(")+'");
                idx += 1;
            }
            else {
                newValue.push(newNodeValue[idx]);
            }
        }
        if (newValue.length !== 0) {
            newValue.push("'");
            newValue.unshift("'");
            const nl = newValue.length;
            if (nl > 2 && newValue[nl - 1] === "'" && newValue[nl - 2] === ")+'") {
                newValue.splice(-2, 2);
                newValue.push(')');
            }
            if (newValue.length > 2 && newValue[0] === "'" && newValue[1] === "'+(") {
                newValue.splice(0, 2);
                newValue.unshift('(');
            }
            newNodeValue = newValue.join('');
        }
    }
    return newNodeValue;
};
exports.getReactiveValue = getReactiveValue;
const isOriginTagOrNativeComp = (tagName, options = {}) => {
    const usedComponentInfo = (options.usingComponents || []).find(item => item.tagName === tagName);
    const isNative = usedComponentInfo && usedComponentInfo.isNative;
    const isOrigin = tagName && typeof tagName === 'string' && tagName.indexOf('origin-') === 0;
    if (isOrigin || isNative) {
        return true;
    }
    return false;
};
exports.isOriginTagOrNativeComp = isOriginTagOrNativeComp;
const parseName = name => {
    const newName = name || 'my-react-component';
    const val = newName.toLowerCase().split('-');
    let str = '';
    val.forEach(v => {
        // eslint-disable-next-line no-param-reassign
        v = v[0].toUpperCase() + v.substr(1);
        str += v;
    });
    return str;
};
exports.parseName = parseName;
// ast遍历相关
const getSiblingPaths = path => {
    const { container } = path;
    const siblingPaths = [];
    for (let i = 0; i < container.length; i += 1) {
        siblingPaths.push(path.getSibling(i));
    }
    return siblingPaths;
};
exports.getSiblingPaths = getSiblingPaths;
const objValueStr2AST = objValueStr => {
    const values = objValueStr.split('.');
    if (values.length === 1)
        return t.identifier(values[0]);
    return t.memberExpression((0, exports.objValueStr2AST)(values.slice(0, values.length - 1).join('.')), (0, exports.objValueStr2AST)(values[values.length - 1]));
};
exports.objValueStr2AST = objValueStr2AST;
const key2ObjCall = (key, value, prefix, index) => {
    if (!index) {
        // eslint-disable-next-line no-param-reassign
        index = 0;
    }
    if (key.length - 1 <= index) {
        return typeof value === 'string' ? (0, exports.objValueStr2AST)(value) : value;
    }
    return t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('assign')), [
        t.objectExpression([]),
        (0, exports.objValueStr2AST)(indexKey2Str(index + 1, key, prefix)),
        t.objectExpression([
            t.objectProperty(t.identifier(key[index + 1]), (0, exports.key2ObjCall)(key, value, prefix, index + 1)),
        ]),
    ]);
    function indexKey2Str(index, key, prefix) {
        const str = prefix.split('.');
        for (let i = 0; i < index; i += 1)
            str.push(key[i]);
        return str.join('.');
    }
};
exports.key2ObjCall = key2ObjCall;
const objPropStr2AST = (key, value) => {
    const newKey = key.split('.');
    return t.objectProperty(t.identifier(newKey[0]), (0, exports.key2ObjCall)(newKey, value, 'this.state'));
};
exports.objPropStr2AST = objPropStr2AST;
const newReplaceAll = (source, key, str, isVariableReplace = false) => {
    const value = key.replace(/\./g, '\\.');
    // 防止会出现两次this.state或者this.props的情况，使用后行断言否定。不是this.state|props的value值才会被匹配到。
    // 再添加两个负向零宽断言，表示排除被单引号或双引号包含的情况。
    if (isVariableReplace)
        return source.replace(new RegExp(`(?<!['"])(?<!this\.(state|props)\.)${value}(?!['"])`, 'g'), str);
    return source.replace(new RegExp(`(?<!['"])${value}(?!['"])`, 'g'), str);
};
exports.newReplaceAll = newReplaceAll;
const getCustomCssList = (cssStr = '') => {
    // 提取所有css选择器
    const arr = [...cssStr.matchAll(/[@.#a-zA-Z][^}]*?(?={)/g)];
    let strArr = [];
    // 提取选择器内的类名单词
    for (const item of arr) {
        item[0].replace(/([0-9A-Za-z_-]+)/g, (match) => { strArr.push(match); });
    }
    // 去重
    let resArr = [...new Set(strArr)];
    return resArr;
};
exports.getCustomCssList = getCustomCssList;
