"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePackagerCommandsInReadme = exports.cleanupExpoRouterConversion = exports.updateExpoRouterSrcDir = exports.refactorExpoRouterReactotronCmds = exports.createExpoRouterScreenTemplate = exports.replaceMaestroBundleIds = exports.renameReactNativeApp = exports.copyBoilerplate = exports.isAndroidInstalled = void 0;
var gluegun_1 = require("gluegun");
var filesystem_ext_1 = require("./filesystem-ext");
var flag_1 = require("./flag");
var packager_1 = require("./packager");
var isAndroidInstalled = function (toolbox) {
    var androidHome = process.env.ANDROID_HOME;
    var hasAndroidEnv = !toolbox.strings.isBlank(androidHome);
    var hasAndroid = hasAndroidEnv && toolbox.filesystem.exists("".concat(androidHome, "/tools")) === "dir";
    return Boolean(hasAndroid);
};
exports.isAndroidInstalled = isAndroidInstalled;
/**
 * Copies the boilerplate over to the destination folder.
 *
 */
function copyBoilerplate(toolbox, options) {
    return __awaiter(this, void 0, void 0, function () {
        var filesystem, copyAsync, path, filesAndFolders, copyTargets, overwrite, copyPromises;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    filesystem = toolbox.filesystem;
                    copyAsync = filesystem.copyAsync, path = filesystem.path;
                    // ensure the destination folder exists
                    return [4 /*yield*/, filesystem.dirAsync(options.targetPath)
                        // rather than copying everything wholesale, let's check what's in the boilerplate folder
                        // and copy over everything except stuff like lockfiles and node_modules
                        // just to make it faster, y'know? Don't want to copy unnecessary stuff
                    ];
                case 1:
                    // ensure the destination folder exists
                    _a.sent();
                    filesAndFolders = (0, filesystem_ext_1.children)(options.boilerplatePath, true);
                    copyTargets = filesAndFolders.filter(function (file) { return !options.excluded.find(function (exclusion) { return file.includes(exclusion); }); });
                    overwrite = options.overwrite;
                    copyPromises = copyTargets.map(function (fileOrFolder) {
                        return copyAsync(path(options.boilerplatePath, fileOrFolder), path(options.targetPath, fileOrFolder), __assign({}, (overwrite && { overwrite: overwrite })));
                    });
                    // copy them all at once
                    return [2 /*return*/, Promise.all(copyPromises)];
            }
        });
    });
}
exports.copyBoilerplate = copyBoilerplate;
function renameReactNativeApp(toolbox, oldName, newName, oldBundleIdentifier, newBundleIdentifier) {
    return __awaiter(this, void 0, void 0, function () {
        function rename(oldFile, newFile) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    log("Renaming ".concat(oldFile, " to ").concat(newFile));
                    return [2 /*return*/, filesystem.renameAsync(oldFile, newFile)];
                });
            });
        }
        var parameters, filesystem, print, strings, kebabCase, path, debug, log, oldnamelower, newnamelower, oldnamekebab, newnamekebab, oldnamesnake, newnamesnake, oldPath, newPath, filesToPatch;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    parameters = toolbox.parameters, filesystem = toolbox.filesystem, print = toolbox.print, strings = toolbox.strings;
                    kebabCase = strings.kebabCase;
                    path = filesystem.path;
                    debug = (0, flag_1.boolFlag)(parameters.options.debug);
                    log = function (m) {
                        debug && print.info(" ".concat(m));
                        return m;
                    };
                    oldnamelower = oldName.toLowerCase();
                    newnamelower = newName.toLowerCase();
                    oldnamekebab = kebabCase(oldName);
                    newnamekebab = kebabCase(newName);
                    oldnamesnake = oldnamelower.replace(/[^a-z0-9]/g, "_").toUpperCase();
                    newnamesnake = newnamelower.replace(/[^a-z0-9]/g, "_").toUpperCase();
                    // rename files and folders
                    // prettier-ignore
                    return [4 /*yield*/, Promise.allSettled([
                            rename("ios/".concat(oldName, ".xcodeproj/xcshareddata/xcschemes/").concat(oldName, ".xcscheme"), "".concat(newName, ".xcscheme")),
                            rename("ios/".concat(oldName, "Tests/").concat(oldName, "Tests.m"), "".concat(newName, "Tests.m")),
                            rename("ios/".concat(oldName, "/").concat(oldName, "-Bridging-Header.h"), "".concat(newName, "-Bridging-Header.h")),
                            rename("ios/".concat(oldName, "/").concat(oldName, ".entitlements"), "".concat(newName, ".entitlements")),
                            rename("ios/".concat(oldName, ".xcworkspace"), "".concat(newName, ".xcworkspace")),
                            rename("ios/".concat(oldName), "".concat(newName)),
                        ])
                        // these we delay to avoid race conditions
                    ];
                case 1:
                    // rename files and folders
                    // prettier-ignore
                    _a.sent();
                    // these we delay to avoid race conditions
                    return [4 /*yield*/, Promise.allSettled([
                            rename("ios/".concat(oldName, "Tests"), "".concat(newName, "Tests")),
                            rename("ios/".concat(oldName, ".xcodeproj"), "".concat(newName, ".xcodeproj")),
                        ])
                        // if the bundle identifier / android package name changed,
                        // we need to move everything to the new folder structure
                    ];
                case 2:
                    // these we delay to avoid race conditions
                    _a.sent();
                    oldPath = oldBundleIdentifier.replace(/\./g, "/");
                    newPath = newBundleIdentifier.replace(/\./g, "/");
                    if (!(oldBundleIdentifier !== newBundleIdentifier)) return [3 /*break*/, 4];
                    log("Renaming bundle identifier to ".concat(newBundleIdentifier));
                    // move everything at the old bundle identifier path to the new one
                    return [4 /*yield*/, Promise.allSettled([
                            filesystem.moveAsync("android/app/src/main/java/".concat(oldPath), "android/app/src/main/java/".concat(newPath)),
                            filesystem.moveAsync("android/app/src/debug/java/".concat(oldPath), "android/app/src/debug/java/".concat(newPath)),
                            filesystem.moveAsync("android/app/src/release/java/".concat(oldPath), "android/app/src/release/java/".concat(newPath)),
                        ])];
                case 3:
                    // move everything at the old bundle identifier path to the new one
                    _a.sent();
                    _a.label = 4;
                case 4:
                    filesToPatch = [
                        "app.json",
                        "package.json",
                        "android/settings.gradle",
                        "android/app/_BUCK",
                        "android/app/BUCK",
                        "android/app/build.gradle",
                        "android/app/src/debug/java/".concat(newPath, "/ReactNativeFlipper.java"),
                        "android/app/src/release/java/".concat(newPath, "/ReactNativeFlipper.java"),
                        "android/app/src/main/AndroidManifest.xml",
                        "android/app/src/main/java/".concat(newPath, "/MainActivity.java"),
                        "android/app/src/main/java/".concat(newPath, "/MainApplication.java"),
                        "android/app/src/main/java/".concat(newPath, "/MainApplication.java"),
                        "android/app/src/main/java/".concat(newPath, "/newarchitecture/MainApplicationReactNativeHost.java"),
                        "android/app/src/main/java/".concat(newPath, "/newarchitecture/components/MainComponentsRegistry.java"),
                        "android/app/src/main/java/".concat(newPath, "/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java"),
                        "android/app/src/main/jni/Android.mk",
                        "android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h",
                        "android/app/src/main/jni/MainComponentsRegistry.h",
                        "android/app/src/main/res/values/strings.xml",
                        "ios/Podfile",
                        "ios/main.jsbundle", // this file could just be regenerated, but this isn't bad to do
                        "ios/".concat(newName, "/Info.plist"),
                        "ios/".concat(newName, ".xcodeproj/project.pbxproj"),
                        "ios/".concat(newName, ".xcodeproj/xcshareddata/xcschemes/").concat(newName, ".xcscheme"),
                        "ios/".concat(newName, ".xcworkspace/contents.xcworkspacedata"),
                        "ios/".concat(newName, "Tests/").concat(newName, "Tests.m"),
                        "ios/".concat(newName, "/AppDelegate.mm"),
                        "ios/".concat(newName, "/LaunchScreen.storyboard"),
                    ];
                    // patch the files
                    return [4 /*yield*/, Promise.allSettled(filesToPatch.map(function (file) { return __awaiter(_this, void 0, void 0, function () {
                            var exists, content, newContent;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, filesystem.existsAsync(path(file))];
                                    case 1:
                                        exists = _a.sent();
                                        if (!exists)
                                            return [2 /*return*/];
                                        return [4 /*yield*/, filesystem.readAsync(path(process.cwd(), file), "utf8")];
                                    case 2:
                                        content = _a.sent();
                                        log("Patching ".concat(file, " - ").concat(oldName, " to ").concat(newName, " and variants"));
                                        newContent = content
                                            .replace(new RegExp(oldBundleIdentifier, "g"), newBundleIdentifier)
                                            .replace(new RegExp(oldnamekebab, "g"), newnamekebab)
                                            .replace(new RegExp(oldnamesnake, "g"), newnamesnake)
                                            .replace(new RegExp(oldName, "g"), newName)
                                            .replace(new RegExp(oldnamelower, "g"), newnamelower);
                                        // write the new content back to the file
                                        return [4 /*yield*/, filesystem.writeAsync(file, newContent, { atomic: true })];
                                    case 3:
                                        // write the new content back to the file
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); }))];
                case 5:
                    // patch the files
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.renameReactNativeApp = renameReactNativeApp;
function replaceMaestroBundleIds(toolbox, oldBundleIdentifier, newBundleIdentifier) {
    return __awaiter(this, void 0, void 0, function () {
        var parameters, filesystem, print, path, debug, log, TARGET_DIR, filesToPatch;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    parameters = toolbox.parameters, filesystem = toolbox.filesystem, print = toolbox.print;
                    path = filesystem.path;
                    debug = (0, flag_1.boolFlag)(parameters.options.debug);
                    log = function (m) {
                        debug && print.info(" ".concat(m));
                        return m;
                    };
                    TARGET_DIR = path(process.cwd());
                    filesToPatch = filesystem.cwd(TARGET_DIR).find({
                        matching: ".maestro/**.yaml",
                        files: true,
                        directories: false,
                    });
                    // patch the files
                    return [4 /*yield*/, Promise.allSettled(filesToPatch.map(function (file) { return __awaiter(_this, void 0, void 0, function () {
                            var exists, content, newContent;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, filesystem.existsAsync(path(file))];
                                    case 1:
                                        exists = _a.sent();
                                        if (!exists)
                                            return [2 /*return*/];
                                        return [4 /*yield*/, filesystem.readAsync(path(process.cwd(), file), "utf8")];
                                    case 2:
                                        content = _a.sent();
                                        log("Patching ".concat(file, " - ").concat(oldBundleIdentifier, " to ").concat(newBundleIdentifier, " and variants"));
                                        newContent = content.replace(new RegExp(oldBundleIdentifier, "g"), newBundleIdentifier);
                                        // write the new content back to the file
                                        return [4 /*yield*/, filesystem.writeAsync(file, newContent, { atomic: true })];
                                    case 3:
                                        // write the new content back to the file
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); }))];
                case 1:
                    // patch the files
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.replaceMaestroBundleIds = replaceMaestroBundleIds;
function createExpoRouterScreenTemplate(toolbox) {
    var filesystem = toolbox.filesystem, parameters = toolbox.parameters, print = toolbox.print;
    // debug?
    var debug = (0, flag_1.boolFlag)(parameters.options.debug);
    var log = function (m) {
        debug && print.info(" ".concat(m));
        return m;
    };
    try {
        var TARGET_DIR = filesystem.path(process.cwd());
        var filePath = filesystem.path(TARGET_DIR, "ignite/templates/screen/NAME.tsx.ejs");
        var EXPO_ROUTER_SCREEN_TPL = "import React, { FC } from \"react\"\nimport { observer } from \"mobx-react-lite\"\nimport { ViewStyle } from \"react-native\"\nimport { Screen, Text } from \"src/components\"\n\n// @mst replace-next-line export default function <%= props.pascalCaseName %>Screen() {\nexport default observer(function <%= props.pascalCaseName %>Screen() {\n  return (\n    <Screen style={$root} preset=\"scroll\">\n      <Text text=\"<%= props.camelCaseName %>\" />\n    </Screen>\n  )\n// @mst replace-next-line }\n})\n\nconst $root: ViewStyle = {\n  flex: 1,\n}\n";
        filesystem.write(filePath, EXPO_ROUTER_SCREEN_TPL);
    }
    catch (e) {
        log("Unable to write screen generator template.");
    }
}
exports.createExpoRouterScreenTemplate = createExpoRouterScreenTemplate;
function refactorExpoRouterReactotronCmds(toolbox) {
    var filesystem = toolbox.filesystem, parameters = toolbox.parameters, print = toolbox.print;
    // debug?
    var debug = (0, flag_1.boolFlag)(parameters.options.debug);
    var log = function (m) {
        debug && print.info(" ".concat(m));
        return m;
    };
    try {
        var TARGET_DIR = filesystem.path(process.cwd());
        var reactotronConfigPath = filesystem.path(TARGET_DIR, "src/devtools/ReactotronConfig.ts");
        var reactotronConfig = filesystem.read(reactotronConfigPath);
        reactotronConfig = reactotronConfig
            .replace(/import { goBack, resetRoot, navigate }.*/g, 'import { router } from "expo-router"')
            .replace(/navigate\(route as any\).*/g, "router.push(route)")
            .replace(/goBack\(\).*/g, " router.back()");
        // this one gets removed entirely
        var customCommandToRemoveRegex = /reactotron\.onCustomCommand\({\s*title: "Reset Navigation State",\s*description: "Resets the navigation state",\s*command: "resetNavigation",\s*handler: \(\) => {\s*Reactotron\.log\("resetting navigation state"\)\s*resetRoot\({ index: 0, routes: \[\] }\)\s*},\s*}\),?\n?/g;
        reactotronConfig = reactotronConfig.replace(customCommandToRemoveRegex, "");
        filesystem.write(reactotronConfigPath, reactotronConfig);
    }
    catch (e) {
        log("Unable to update ReactotronConfig.");
    }
}
exports.refactorExpoRouterReactotronCmds = refactorExpoRouterReactotronCmds;
function updateExpoRouterSrcDir(toolbox) {
    var filesystem = toolbox.filesystem, parameters = toolbox.parameters, print = toolbox.print;
    // debug?
    var debug = (0, flag_1.boolFlag)(parameters.options.debug);
    var log = function (m) {
        debug && print.info(" ".concat(m));
        return m;
    };
    var TARGET_DIR = filesystem.path(process.cwd());
    var expoRouterFilesToFix = [
        "tsconfig.json",
        // has its own tsconfig, needs updating separately
        "test/i18n.test.ts",
        "test/setup.ts",
        "ignite/templates/model/NAME.ts.ejs",
        "ignite/templates/model/NAME.test.ts.ejs",
        "ignite/templates/component/NAME.tsx.ejs",
    ];
    expoRouterFilesToFix.forEach(function (file) {
        var filePath = filesystem.path(TARGET_DIR, file);
        var fileContents = filesystem.read(filePath);
        try {
            fileContents = fileContents.replace(/app\//g, "src/");
            filesystem.write(filePath, fileContents);
        }
        catch (e) {
            log("Unable to locate ".concat(file, "."));
        }
    });
}
exports.updateExpoRouterSrcDir = updateExpoRouterSrcDir;
function cleanupExpoRouterConversion(toolbox, targetPath) {
    var filesystem = toolbox.filesystem;
    var workingDir = filesystem.cwd(targetPath);
    workingDir.cwd("src").remove("app.tsx");
    workingDir.move(workingDir.path("src", "screens", "ErrorScreen"), workingDir.path("src", "components", "ErrorBoundary"));
    workingDir.remove("index.tsx");
    workingDir.remove(workingDir.path("ignite", "templates", "screen", "NAMEScreen.tsx.ejs"));
    workingDir.remove(workingDir.path("ignite", "templates", "navigator"));
    workingDir.remove(workingDir.path("src", "screens"));
    workingDir.remove(workingDir.path("src", "navigators"));
    workingDir.remove("app");
}
exports.cleanupExpoRouterConversion = cleanupExpoRouterConversion;
function updatePackagerCommandsInReadme(readmePath, packagerName) {
    try {
        var readmeContents = gluegun_1.filesystem.read(readmePath);
        // replace `yarn` exactly with the install command
        readmeContents = readmeContents.replace("yarn", packager_1.packager.installCmd({ packagerName: packagerName }));
        // replace `yarn` plus some command after the space with the proper packager run command
        // pass the matched command to runCmd as string excluding the `yarn` part
        readmeContents = readmeContents.replace(/^yarn\s(.*)$/gm, function (_, cmd) {
            return packager_1.packager.runCmd(cmd, { packagerName: packagerName });
        });
        gluegun_1.filesystem.write(readmePath, readmeContents);
    }
    catch (e) {
        console.error("Unable to update README.md.");
    }
}
exports.updatePackagerCommandsInReadme = updatePackagerCommandsInReadme;
//# sourceMappingURL=react-native.js.map