"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __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 });
const parser_1 = require("@babel/parser");
const traverse_1 = __importDefault(require("@babel/traverse"));
const generator_1 = __importDefault(require("@babel/generator"));
const types = __importStar(require("@babel/types"));
class ImportManager {
    code;
    ast;
    imports;
    constructor(code) {
        this.code = code;
        this.ast = null;
        this.imports = [];
        this._parse();
    }
    _parse() {
        if (!this.code) {
            this.ast = { program: { body: [] } };
            return;
        }
        // 解析源码为 AST
        this.ast = (0, parser_1.parse)(this.code, {
            sourceType: 'module'
        });
        this._collectImports();
    }
    _collectImports() {
        this.imports = [];
        (0, traverse_1.default)(this.ast, {
            ImportDeclaration: (path) => {
                const source = path.node.source.value;
                const specifiers = path.node.specifiers.map(specifier => {
                    if (specifier.type === 'ImportDefaultSpecifier') {
                        return specifier.local.name;
                    }
                    else if (specifier.type === 'ImportSpecifier') {
                        if (specifier.imported.type == "Identifier")
                            return specifier.imported.name;
                        return specifier.imported.value;
                    }
                    else if (specifier.type === 'ImportNamespaceSpecifier') {
                        return '*' + specifier.local.name; // * as name
                    }
                    return null;
                }).filter(name => name !== null);
                this.imports.push({
                    moduleName: source,
                    importItem: specifiers
                });
            }
        });
    }
    // 检查是否导入了某个包
    has(moduleName) {
        return this.imports
            .some(imp => imp.moduleName === moduleName);
    }
    // 返回所有导入包
    get() {
        return this.imports.map(imp => ({
            ModuleName: imp.moduleName,
            ImportItem: [...imp.importItem]
        }));
    }
    // 设置/修改导入项
    set({ ModuleName, ImportItem }) {
        // 查找是否已有该包，或有相同的包名或导入项
        const exists = this.imports.findIndex(imp => imp.moduleName === ModuleName ||
            imp.importItem.some(item => ImportItem.includes(item)));
        if (exists > -1) {
            // 修改已存在的项
            this.imports[exists] = {
                moduleName: ModuleName,
                importItem: [...ImportItem]
            };
        }
        else {
            // 新增
            this.imports.push({
                moduleName: ModuleName,
                importItem: [...ImportItem]
            });
        }
        // 同步更新 AST
        this._syncAST();
    }
    // 同步 imports 数据到 AST
    _syncAST() {
        // 先删除所有 import 声明
        (0, traverse_1.default)(this.ast, {
            ImportDeclaration(path) {
                path.remove();
            }
        });
        // 重新插入 import 声明
        this.imports.forEach(imp => {
            const specifiers = [];
            imp.importItem.forEach(name => {
                if (name === '*') {
                    // 处理 * as xx 的情况
                    const match = name.match(/\*\s+as\s+(\w+)/) || [];
                    if (match)
                        specifiers.push(types.importNamespaceSpecifier(types.identifier(match[1] || "")));
                }
                else if (name.endsWith('*')) {
                    // 默认导入
                    specifiers
                        .push(types.importDefaultSpecifier(types.identifier(name.replace('*', ''))));
                }
                else {
                    specifiers
                        .push(types.importSpecifier(types.identifier(name), types.identifier(name)));
                }
            });
            // 构造 ImportDeclaration 节点
            const importNode = types.importDeclaration(specifiers, types.stringLiteral(imp.moduleName));
            this.ast.program.body.unshift(importNode);
        });
    }
    // 生成最终代码
    generate() {
        return (0, generator_1.default)(this.ast, {
            compact: false
        }).code;
    }
}
exports.default = ImportManager;
