//babel库及文件模块导入
const fs = require('fs');

//babel库相关，解析，转换，构建，生产
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const types = require("@babel/types");
// const {replaceWith} = require("cheerio/lib/api/manipulation");
const generator = require("@babel/generator").default;

// const YY = require('./test')
// console.log(YY)
//读取文件
let encode_file = "./sss.js",
    decode_file = "./src_out.js";
// let encode_file = "./jiyan.js",decode_file = "./decode_result.js";
if (process.argv.length > 2) {
    encode_file = process.argv[2];
}
if (process.argv.length > 3) {
    decode_file = process.argv[3];
}

let jscode = fs.readFileSync(encode_file, { encoding: "utf-8" });
//转换为ast树
let ast = parser.parse(jscode);

traverse(ast, {
    VariableDeclaration(path){
        let node = path.node;
        let declarations = node.declarations;
        if (declarations.length == 0 && types.isVariableDeclarator(declarations[0])){}
        let variable = declarations[0]
        let {id, init} = variable;
        if (types.isArrayExpression(init) && init.elements.length > 100){
            let eles = init.elements;
            let hasNotFunc = false;
            eles.forEach(e=>{
                if (!types.isFunctionExpression(e)){
                    hasNotFunc = true
                }
            })
            if (hasNotFunc)return;
            let cases = []
            eles.forEach((e,i)=>{
                cases.push(types.SwitchCase(types.NumericLiteral(i), [types.ReturnStatement(e)]))
            })
            console.log()

            let res = types.FunctionDeclaration(id,[types.Identifier('key')], types.BlockStatement([types.SwitchStatement(types.Identifier('key'), cases)]))
            path.replaceWith(res)
        }

    }
})

let { code } = generator(ast, {
    minified:false,
    // jsescOption:{
    //     quotes: "double",
    //     wrap: true,
    //     minimal: false
    // }

});
fs.writeFile(decode_file, code, (err) => {});