"use strict";
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var recast = require("recast");
var prettier = require("prettier");
var utils_1 = require("../utils");
var _a = recast.types, namedTypes = _a.namedTypes, builders = _a.builders, visit = _a.visit;
exports.default = function (options) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
    var src, dest, editor, hasCommonJS, appJS, code, ast, topLevelReturnStatementPath, iifePath, requireProcessor, indexTpl, destJS;
    return tslib_1.__generator(this, function (_a) {
        src = options.get("src");
        dest = options.get("dest");
        editor = options.get("editor");
        hasCommonJS = options.get("hasCommonJS");
        appJS = editor.read(src + "/app.js");
        code = "\n    (function() {\n      return {\n        /* no-op */\n      };\n    }());\n  ";
        ast = recast.parse(appJS);
        visit(ast, {
            visitReturnStatement: function (path) {
                if (!topLevelReturnStatementPath) {
                    topLevelReturnStatementPath = path;
                }
                else if (path.scope.depth <= topLevelReturnStatementPath.scope.depth) {
                    // Check that the argument to the return statement _is_ actually an object
                    if (!namedTypes.ObjectExpression.check(path.node.argument)) {
                        return false;
                    }
                    topLevelReturnStatementPath = path;
                }
                this.traverse(path);
            }
        });
        if (topLevelReturnStatementPath) {
            iifePath = topLevelReturnStatementPath.parent.parent.parent.parent;
            if (namedTypes.ExpressionStatement.assert(iifePath.node)) {
                ast.program = builders.program([iifePath.node]);
            }
            // Generate the final JavaScript for the app subclass definition
            code = recast.print(ast).code;
            // Check whether the migrate_common_js step discovered some Common JS files
            if (hasCommonJS) {
                requireProcessor = utils_1.requireStatementProcessorFactory(options, false);
                code = requireProcessor(code, src + "/app.js");
            }
        }
        indexTpl = "./src/templates/legacy_app.ejs";
        destJS = dest + "/src/javascripts/legacy_app.js";
        editor.copyTpl(indexTpl, destJS, { code: code });
        // FIXME: Unfortunately, `copyTpl` doesn't work as advertised,
        // it _should_ allow a process function that would make it possible
        // to format the contents of the file during the copy operation... :(
        editor.write(destJS, prettier.format(editor.read(destJS)));
        return [2 /*return*/];
    });
}); };
