"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenTranspiler = void 0;
const css_to_react_native_transform_1 = __importDefault(require("css-to-react-native-transform"));
const lodash_1 = require("lodash");
const style_definition_provider_1 = require("./components/style-definition.provider");
const rn_stylesheet_transpiler_1 = require("./rn-stylesheet.transpiler");
const csstree = __importStar(require("css-tree"));
class TokenTranspiler {
    parseRNValues(body) {
        const rBody = body.replace(/:\s*var\(\s*--/g, '_var:var(--');
        const tokens = (0, css_to_react_native_transform_1.default)(`.style${rBody}`).style;
        Object.keys(tokens).forEach(k => {
            if ((0, lodash_1.isString)(k) && (k.endsWith('Var') || k.endsWith('_var'))) {
                const normalizedKey = k.replace(/(Var|_var)$/, '');
                tokens[normalizedKey] = tokens[k];
                delete tokens[k];
            }
        });
        return tokens || {};
    }
    mergeAtPath(root, pathParts, tokens) {
        let current = root;
        for (let i = 0; i < pathParts.length; i++) {
            const key = pathParts[i];
            if (i === pathParts.length - 1) {
                current[key] = { ...(current[key] || {}), ...tokens };
            }
            else {
                current[key] = current[key] || {};
                current = current[key];
            }
        }
    }
    getColorSchemes(rnstylesheet) {
        const ast = csstree.parse(rnstylesheet);
        const colorSchemes = [];
        const variants = {};
        let currentScheme = {
            name: 'light',
            tokens: {}
        };
        colorSchemes.push(currentScheme);
        csstree.walk(ast, {
            enter: (node) => {
                if (node.type === 'Rule') {
                    const selector = csstree.generate(node.prelude).trim();
                    const body = csstree.generate(node.block || { type: 'Block', children: [] });
                    let fixedBody = body;
                    if (!/\{[\s]*\}/.test(fixedBody) && !fixedBody.endsWith(';}')) {
                        fixedBody = fixedBody.replace('}', ';}');
                    }
                    const tokens = this.parseRNValues(fixedBody);
                    if (selector === ':root') {
                        Object.assign(currentScheme.tokens, tokens);
                    }
                    else if (selector.startsWith('.')) {
                        const className = selector.replace(/^\./, '');
                        variants[className] = tokens;
                    }
                }
            }
        });
        return { colorSchemes, variants };
    }
    getOverrideColorSchemes(rnstylesheet) {
        const colorSchemes = [];
        const variants = {};
        let currentScheme = {
            name: 'light',
            tokens: {}
        };
        colorSchemes.push(currentScheme);
        const rules = new rn_stylesheet_transpiler_1.RnStylesheetTranspiler().getRules(rnstylesheet);
        rules.forEach(rule => {
            const tokens = this.parseRNValues(rule.body);
            rule.selectors.forEach(selectorClasses => {
                if (selectorClasses.length === 0) {
                    // :root
                    Object.assign(currentScheme.tokens, tokens);
                    return;
                }
                const fullKey = selectorClasses.map(c => c.replace(/^\./, '')).join('.');
                variants[fullKey] = { ...(variants[fullKey] || {}), ...tokens };
                // Handling custom variants
                if (selectorClasses.length > 1) {
                    const firstClass = selectorClasses[0].replace(/^\./, '');
                    const remainingClasses = selectorClasses.slice(1);
                    // Initialize the first class key if it doesn't exist
                    if (!variants[firstClass]) {
                        variants[firstClass] = {};
                    }
                    //creating nested structure
                    const rnMappedIndices = [];
                    remainingClasses.forEach((cls, idx) => {
                        const rnPath = (0, style_definition_provider_1.getRNSelector)(cls);
                        if (rnPath) {
                            rnMappedIndices.push(idx);
                        }
                    });
                    if (rnMappedIndices.length) {
                        rnMappedIndices.forEach(idx => {
                            const rnPath = (0, style_definition_provider_1.getRNSelector)(remainingClasses[idx]);
                            const parts = rnPath.split('.');
                            // skip component name if custom variant
                            if (parts.length > 1) {
                                const nestedParts = parts.slice(1);
                                this.mergeAtPath(variants[firstClass], nestedParts, tokens);
                            }
                            else {
                                variants[firstClass][parts[0]] = { ...(variants[firstClass][parts[0]] || {}), ...tokens };
                            }
                        });
                    }
                }
                else {
                    // single class selector check if RN selector is available
                    const className = selectorClasses[0].replace(/^\./, '');
                    const rnPath = (0, style_definition_provider_1.getRNSelector)(selectorClasses[0]);
                    if (rnPath) {
                        const parts = rnPath.split('.');
                        this.mergeAtPath(variants, parts, tokens);
                    }
                    else {
                        variants[className] = { ...(variants[className] || {}), ...tokens };
                    }
                }
            });
        });
        return { colorSchemes, variants };
    }
}
exports.TokenTranspiler = TokenTranspiler;
//# sourceMappingURL=token.transpiler.js.map