"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = __importDefault(require("debug"));
const to_field_1 = require("./to-field");
const type_parse_1 = require("../../util/type-parse");
const transfer_1 = require("./util/transfer");
const log = debug_1.default('j2t:core:toBeanClass');
/**
 * java接口转换为ts接口ast
 * @param typeDef
 * @returns {InterfaceDeclarationStructure}
 */
async function toBeanClass(typeDef, intepretHandle) {
    log('调用转换方法 toBeanClass::');
    let typeName = intepretHandle.getTypeInfo(typeDef.name).className;
    let typeParameters = [];
    if (typeDef.typeParams) {
        typeDef.typeParams.forEach(typeParamsItem => {
            typeParameters.push({ name: typeParamsItem.name + "=any", });
        });
    }
    //获取 方法定义; 或者获取属性定义
    let methods = [], properties = [], ctorParams = [];
    //1.1 找到实例中的相关参数及类型
    let fileds = [];
    for (var fieldName in typeDef.fields) {
        //有些字段类型为org.slf4j.Logger等信息;;;我们要转化的应该只是
        let filedType = typeDef.fields[fieldName].name;
        if (typeDef.fields[fieldName].isArray) {
            filedType = typeDef.fields[fieldName].elementType.name;
        }
        let field = await to_field_1.toField(fieldName, typeDef.fields[fieldName], intepretHandle);
        properties.push(field);
        ctorParams.push({ name: field.name, type: field.type });
        let filedItem = typeDef.fields[fieldName];
        fileds.push({
            name: fieldName,
            type: await type_parse_1.jType2Ts(filedItem, intepretHandle),
            filedAst: filedItem,
        });
    }
    //添加构造函数入参interface
    //1.2 生成方法;;
    let { fieldTrans, initContent } = await transfer_1.fields2CtrContent(fileds, intepretHandle, typeDef);
    let bodyText = `${initContent ? initContent + ';' : ''}
      return {
            $class: '${typeDef.name}', 
            $: {${fieldTrans.join(',')}}
      }`;
    try {
        intepretHandle.sourceFile.addInterface({
            typeParameters,
            isExported: true,
            name: 'I' + typeName,
            properties,
        });
    }
    catch (err) {
        console.error(`为${intepretHandle.classPath}添加Interface出错,${err}`);
    }
    methods.push({ name: '__fields2java', bodyText });
    let ctorBody = ctorParams
        .map(({ name }) => `this.${name}=params.${name};`)
        .join('\n');
    return {
        name: typeName,
        ctor: {
            parameters: [
                {
                    name: `params:${transfer_1.getCtorParaStr(typeName, typeParameters)}`,
                },
            ],
            bodyText: ctorBody,
        },
        typeParameters,
        properties,
        isExported: true,
        methods,
    };
}
exports.toBeanClass = toBeanClass;
