"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = require("path");
const lodash_1 = require("lodash");
const execa_1 = __importDefault(require("execa"));
const transpile_1 = require("./transpile/transpile");
const variable_transformer_1 = __importDefault(require("./variables/variable.transformer"));
const utils_1 = require("./utils");
const bind_ex_transformer_1 = __importDefault(require("./transpile/bind.ex.transformer"));
const theme_service_1 = require("./theme/theme.service");
const profile_1 = __importDefault(require("./profiles/profile"));
const APP_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/app.template');
const BOOTSTRAP_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/bootstrap.template');
const RESOURCE_RESOLVER_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/resource.resolver.template');
const COMPONENT_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/component/component.template');
const COMPONENT_PROPS_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/component/component.props.template');
const SCRIPT_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/component/script.template');
const STYLE_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/component/style.template');
const PAGE_CONFIG_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/pages-config.template');
const SERVICE_DEFINITIONS = (0, utils_1.loadTemplate)(__dirname + '/templates/service.defs.template');
const VARIABLE_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/variables.template');
const DEVICE_SERVICES_TEMPLATE = (0, utils_1.loadTemplate)(__dirname + '/templates/device-operation-loader.template');
const ALL_GENERATED_FILES = '(src/**/*.js|app.js|app.style.js|bootstrap.js)';
// REF: https://github.com/facebook/metro/blob/master/packages/metro-config/src/defaults/defaults.js#L14-L44
const ALLOWED_RESOURCE_EXT = [
    // Image formats
    'bmp', 'gif', 'jpg', 'jpeg', 'png', 'psd', 'svg', 'webp',
    // Video formats
    'm4v', 'mov', 'mp4', 'mpeg', 'mpg', 'webm',
    // Audio formats
    'aac', 'aiff', 'caf', 'm4a', 'mp3', 'wav',
    // Document formats
    'html', 'pdf', 'yaml', 'yml', 'json',
    // Font formats
    'otf', 'ttf',
    // Archives (virtual files)
    'zip',
];
const pluginOperationConfig = [];
const operationMap = {
    'captureImage': { name: 'Camera', method: 'CaptureImageOperation', filename: 'capture-image', hasConstructorParams: true },
    'captureVideo': { name: 'Camera', method: 'CaptureVideoOperation', filename: 'capture-video', hasConstructorParams: true },
    'scanBarCode': { name: 'Scan', method: 'ScanOperation', filename: 'scan', hasConstructorParams: true },
    'getAppInfo': { name: 'Device', method: 'AppInfoOperation', filename: 'app-info', hasConstructorParams: false },
    'getDeviceInfo': { name: 'Device', method: 'DeviceInfoOperation', filename: 'device-info', hasConstructorParams: false },
    'getNetworkInfo': { name: 'Device', method: 'NetworkInfoOperation', filename: 'network-info', hasConstructorParams: false },
    'vibrate': { name: 'Device', method: 'VibrateOperation', filename: 'vibrate', hasConstructorParams: false },
    'getCurrentGeoPosition': { name: 'Location', method: 'CurrentGeoPositionOperation', filename: 'current-geo-position', hasConstructorParams: true },
    'getContacts': { name: 'Contacts', method: 'GetContactsOperation', filename: 'get-contacts', hasConstructorParams: true },
    'getEvents': { name: 'Calendar', method: 'GetEventsOperation', filename: 'get-events', hasConstructorParams: true },
    'createEvent': { name: 'Calendar', method: 'CreateEventOperation', filename: 'create-event', hasConstructorParams: true },
    'deleteEvent': { name: 'Calendar', method: 'DeleteEventOperation', filename: 'delete-event', hasConstructorParams: true },
    'upload': { name: 'File', method: 'UploadFileOperation', filename: 'upload-file', hasConstructorParams: false },
};
const serviceParams = {
    'Camera': [{
            name: 'AppDisplayManagerService',
            filename: 'app-display-manager.service'
        }],
    'Scan': [{
            name: 'AppDisplayManagerService',
            filename: 'app-display-manager.service'
        }],
    'Location': [],
    'Contacts': [],
    'Calendar': []
};
let deviceVariables = [];
let appVersion;
const servicesConfig = [];
class AppGenerator {
    constructor(projectPath, projectService, appUrl, prefabName = '', dynamicPrefabProps) {
        this.projectPath = projectPath;
        this.projectService = projectService;
        this.appUrl = appUrl;
        this.prefabName = prefabName;
        this.dynamicPrefabProps = dynamicPrefabProps;
        this.transpiledComponents = {
            pages: {},
            partials: {},
            prefabs: {}
        };
        this.isPrefabApp = false;
        this.themeService = new theme_service_1.ThemeService();
        this.isPrefabApp = !!prefabName;
    }
    prepareVariables(variableJSON, scope, imports) {
        const variables = Object.values(variableJSON)
            .map((v) => (0, variable_transformer_1.default)(v, scope, this.appUrl)).filter(v => !!v);
        return VARIABLE_TEMPLATE({
            scope: scope,
            imports: imports,
            isPrefabApp: this.isPrefabApp,
            prefabName: this.prefabName,
            context: {
                Variables: variables.filter(v => v.type === 'variable'),
                Actions: variables.filter(v => v.type === 'action')
            }
        });
    }
    getFilePath(name) {
        let nameArr = name.split('');
        const index = nameArr.findIndex(character => {
            return (character === character.toUpperCase() && character !== '-');
        });
        if (index === -1) {
            return name;
        }
        if (index === 0) {
            name = name[index].toLowerCase() + name.substring(index + 1);
        }
        else {
            name = name.substring(0, index) + '-' + name[index].toLowerCase() + name.substring(index + 1);
        }
        return this.getFilePath(name);
    }
    generatePluginsOperationConfig() {
        const servicesList = [];
        deviceVariables.forEach((v) => {
            const hasEntry = pluginOperationConfig.find(p => p.operation === v.operation);
            if (hasEntry) {
                return false;
            }
            const selectedOperation = operationMap[v.operation];
            if (!selectedOperation) {
                console.log('Cannot find operation named ' + v.operation);
            }
            const excludeServices = ['Device', 'File'];
            if (!servicesList.includes(selectedOperation.name) && !excludeServices.includes(selectedOperation.name)) {
                servicesList.push(selectedOperation.name);
            }
            pluginOperationConfig.push({
                'operation': v.operation,
                'service': v.service,
                'filename': selectedOperation.filename,
                'method': selectedOperation.method,
                'hasparams': selectedOperation.hasConstructorParams,
                'type': selectedOperation.name
            });
        });
        let uniqueImports = [];
        servicesList.forEach((s) => {
            const item = serviceParams[s] || [];
            if (item && item.length) {
                item.forEach((e) => {
                    var itemName = e.name;
                    const isImported = uniqueImports.length && uniqueImports.find(i => {
                        return i.name === itemName;
                    });
                    if (!isImported) {
                        uniqueImports.push(e);
                    }
                });
            }
            servicesConfig.push({
                name: s,
                constructorParams: item,
                servicesStr: '',
                filePath: ''
            });
        });
        servicesConfig.forEach((item) => {
            let servicesStr = '';
            item.constructorParams.forEach((o) => {
                const serviceName = o['name'];
                if (serviceName) {
                    if (!servicesStr) {
                        servicesStr = servicesStr + serviceName;
                    }
                    if (!servicesStr.includes(serviceName)) {
                        servicesStr = servicesStr + ', ' + serviceName;
                    }
                }
            });
            item.servicesStr = servicesStr;
            item.filePath = this.getFilePath(item.name);
        });
        const output = DEVICE_SERVICES_TEMPLATE({
            pluginOperationConfig: pluginOperationConfig,
            appVersion: appVersion,
            servicesConfig: servicesConfig,
            imports: uniqueImports
        });
        (0, utils_1.writeFile)(`${this.projectPath}/src/device-operation-loader.js`, output);
    }
    prepareDeviceOperationLoader() {
        const config = fs_extra_1.default.readJsonSync(`${this.projectPath}/wm_rn_config.json`, {
            encoding: 'utf8'
        });
        appVersion = config.version;
        this.generatePluginsOperationConfig();
    }
    isPartial(type) {
        return type === 'PARTIAL' || type === 'LEFTNAV' || type === 'POPOVER';
    }
    prettify(target = ALL_GENERATED_FILES) {
        let prettierPath = null;
        let d = __dirname;
        while (d) {
            prettierPath = d + path_1.sep + 'node_modules' + path_1.sep + 'prettier';
            if (fs_extra_1.default.existsSync(prettierPath)) {
                break;
            }
            const s = d.split(path_1.sep);
            s.pop();
            d = s.join(path_1.sep);
        }
        if (d) {
            return (0, execa_1.default)('node', [`${prettierPath}${path_1.sep}bin-prettier.js`, '--write', `${this.projectPath}/${target}`]);
        }
        console.warn('Prettier is not found');
        return Promise.reject();
    }
    setDeviceVariables(variables) {
        variables = Object.values(variables);
        const filterOutput = variables.filter((v) => v.category === 'wm.DeviceVariable');
        deviceVariables = deviceVariables.concat(filterOutput);
    }
    savePageDesignStyles(designStyles, pageName) {
        const p = `${this.projectPath}/designtime/pages/${pageName}`;
        fs_extra_1.default.mkdirpSync(p);
        fs_extra_1.default.writeFileSync(`${p}/${pageName}.css`, designStyles);
        return Promise.resolve();
    }
    saveAppDesignStyles(designStyles) {
        const p = `${this.projectPath}/designtime`;
        fs_extra_1.default.mkdirpSync(p);
        fs_extra_1.default.writeFileSync(`${p}/app.css`, designStyles);
        return Promise.resolve();
    }
    generateAppVariables() {
        return this.projectService.getAppVariables().then(variables => {
            this.setDeviceVariables(variables);
            const output = this.prepareVariables(variables, 'App', []);
            (0, utils_1.writeFile)(`${this.projectPath}/src/app.variables.js`, output);
        });
    }
    generateRNConfig() {
        return this.projectService.getRNConfig().then(data => {
            var _a;
            const config = JSON.parse(data);
            if (profile_1.default.generateWeb) {
                config.serverPath = '..';
            }
            else if ((_a = config.serverPath) === null || _a === void 0 ? void 0 : _a.startsWith('http://NOSERVERREQUIRED.com')) {
                config.serverPath = null;
            }
            (0, utils_1.writeFile)(`${this.projectPath}/wm_rn_config.json`, JSON.stringify(config, null, 4));
        });
    }
    generateAppScript() {
        return this.projectService.getAppVariables().then(variables => {
            return this.projectService.getAppJs().then(script => {
                const output = APP_TEMPLATE({
                    script: script,
                    startUpVariables: Object.values(variables).filter((v) => (v.startUpdate || v.category === 'wm.Variable') && v.category !== 'wm.TimerVariable').map((v) => v.name),
                    startUpActions: Object.values(variables).filter((v) => v.startUpdate && v.category === 'wm.TimerVariable').map((v) => v.name),
                    autoUpdateVariables: Object.values(variables).filter((v) => v.autoUpdate || (v.category === 'wm.Variable' && v.dataBinding && v.dataBinding.length)).map((v) => v.name)
                });
                (0, utils_1.writeFile)(`${this.projectPath}/App.js`, output);
            });
        });
    }
    generatePageConfig(pageConfigs) {
        pageConfigs = pageConfigs.filter((p) => p.type == 'PAGE');
        const output = PAGE_CONFIG_TEMPLATE({
            pageConfigs: pageConfigs,
            pageConfigsStr: JSON.stringify(pageConfigs),
            lazyload: profile_1.default.lazyloadPages
        });
        (0, utils_1.writeFile)(`${this.projectPath}/src/pages/pages-config.js`, output);
    }
    generatePartialConfig(pageConfigs) {
        pageConfigs = pageConfigs.filter((p) => this.isPartial(p.type));
        const output = PAGE_CONFIG_TEMPLATE({
            pageConfigs: pageConfigs,
            pageConfigsStr: JSON.stringify(pageConfigs),
            lazyload: profile_1.default.lazyloadPartials
        });
        (0, utils_1.writeFile)(`${this.projectPath}/src/partials/partial-config.js`, output);
    }
    transformStyle(styles) {
        if (!styles) {
            return '{}';
        }
        const splitStr = '/*REACT_NATIVE_STYLES*/';
        const splitAt = styles.indexOf(splitStr);
        if (splitAt > 0) {
            styles = styles.substr(splitAt + splitStr.length);
        }
        return this.themeService.generateReactNativeStyles(styles);
    }
    generateDesignStyles(styles) {
        if (!styles) {
            return '';
        }
        return this.themeService.generateStudioStyles(styles);
    }
    generateComponent(info, type, name) {
        const lType = type.toLowerCase();
        const typeLabel = (0, lodash_1.capitalize)(type);
        const variables = JSON.parse(info.variables);
        this.setDeviceVariables(variables);
        const dest = type === 'PREFAB' ? `${this.projectPath}/src/pages/${name}` : `${this.projectPath}/src/${lType}s/${name}`;
        try {
            const output = this.prepareVariables(variables, typeLabel, []);
            (0, utils_1.writeFile)(`${dest}/${name}.variables.js`, output);
            const transpiledOutput = (0, transpile_1.transpileMarkup)(info.markup, this.isPrefabApp);
            if (this.isPrefabApp) {
                transpiledOutput.imports.forEach(i => {
                    if (i.from.indexOf('/prefabs/') > 0) {
                        i.from = '../../../' + i.from;
                    }
                });
            }
            const imports = (0, lodash_1.sortBy)((0, lodash_1.uniqBy)(transpiledOutput.imports, i => i.name + i.from), i => i.name);
            const component = COMPONENT_TEMPLATE({
                name: name,
                type: type,
                lType: lType,
                typeLabel: typeLabel,
                dynamicPrefabProps: this.dynamicPrefabProps || {},
                prefabName: this.prefabName,
                markup: '\n' + transpiledOutput.markup,
                components: transpiledOutput.components,
                startUpVariables: Object.values(variables).filter((v) => v.startUpdate && v.category !== 'wm.TimerVariable').map((v) => v.name),
                startUpActions: Object.values(variables).filter((v) => v.startUpdate && v.category === 'wm.TimerVariable').map((v) => v.name),
                autoUpdateVariables: Object.values(variables).filter((v) => v.autoUpdate || (v.category === 'wm.Variable' && v.dataBinding && v.dataBinding.length)).map((v) => v.name),
                eagerImports: imports.filter(i => !i.lazy),
                lazyImports: imports.filter(i => i.lazy)
            });
            (0, utils_1.writeFile)(`${dest}/${name}.component.js`, component);
            const script = SCRIPT_TEMPLATE({
                typeLabel: typeLabel,
                script: info.script
            });
            (0, utils_1.writeFile)(`${dest}/${name}.script.js`, script);
            const styles = STYLE_TEMPLATE({
                styles: this.transformStyle(info.styles)
            });
            (0, utils_1.writeFile)(`${dest}/${name}.style.js`, styles);
            if (profile_1.default.generateWeb) {
                this.savePageDesignStyles(this.generateDesignStyles(info.styles), name);
            }
            return Promise.all(transpiledOutput.prefabs.map(p => this.generatePrefabComponent(p, false)));
        }
        catch (e) {
            console.log(`failed to generate component ${dest}/${name}`);
            throw e;
        }
    }
    generatePrefabProps(name, projectPath) {
        const dynamicProps = {};
        return this.projectService.getPrefabInfo(name)
            .then(info => {
            const propConfig = {};
            Object.keys(info.config.properties).map((k) => {
                const value = info.config.properties[k].value;
                if ((0, lodash_1.isString)(value) && value.startsWith('bind:')) {
                    let exStr = decodeURIComponent(value.substring(5));
                    dynamicProps[k] = `this.eval(() => ${(0, bind_ex_transformer_1.default)(exStr, '_this', 'attr')})`;
                    propConfig[k] = null;
                }
                else {
                    propConfig[k] = value === undefined ? null : value;
                }
            });
            const props = COMPONENT_PROPS_TEMPLATE({
                props: JSON.stringify(propConfig)
            });
            (0, utils_1.writeFile)(`${projectPath}/src/prefabs/${name}/src/pages/Main/Main.props.js`, props);
            return dynamicProps;
        });
    }
    generatePrefabComponent(name, overwrite = true) {
        if (!overwrite && this.transpiledComponents.prefabs[name]) {
            return Promise.resolve();
        }
        const projectPath = this.isPrefabApp ? this.projectPath.split('/src/prefabs/')[0] : this.projectPath;
        const appUrl = this.isPrefabApp ? this.appUrl.split('/app/prefabs/')[0] : this.appUrl;
        this.transpiledComponents.prefabs[name] = true;
        return this.generatePrefabProps(name, projectPath).then(dynamicPrefabProps => {
            const prefabGenerator = new AppGenerator(`${projectPath}/src/prefabs/${name}`, this.projectService.getPrefabProjectService(name), `${appUrl}/app/prefabs/${name}`, name, dynamicPrefabProps);
            return prefabGenerator.generatePagesAndPartials()
                .then(() => prefabGenerator.generateResourceResolver());
        });
    }
    generatePageComponent(name, overwrite = true) {
        if (!overwrite && this.transpiledComponents.pages[name]) {
            return Promise.resolve();
        }
        this.transpiledComponents.pages[name] = true;
        return this.projectService.getPageInfo(name).then(info => {
            return this.generateComponent(info, this.isPrefabApp ? 'PREFAB' : 'PAGE', name);
        });
    }
    generatePartialComponent(name, overwrite = true) {
        if (!overwrite && this.transpiledComponents.partials[name]) {
            return Promise.resolve();
        }
        this.transpiledComponents.partials[name] = true;
        return this.projectService.getPageInfo(name).then(info => {
            return this.generateComponent(info, 'PARTIAL', name);
        });
    }
    generateServiceDefs() {
        return this.projectService.getServiceDefs().then(serviceDefs => {
            const output = SERVICE_DEFINITIONS({ serviceDefs: JSON.stringify(serviceDefs) });
            (0, utils_1.writeFile)(`${this.projectPath}/src/service-definitions.js`, output);
        });
    }
    generateBootstrapScript() {
        const config = fs_extra_1.default.readJsonSync(`${this.projectPath}/wm_rn_config.json`, {
            encoding: 'utf8'
        });
        let appUrl = this.appUrl;
        if (!(0, lodash_1.isEmpty)(config.serverPath) && config.serverPath !== '{{DEVELOPMENT_URL}}') {
            appUrl = config.serverPath;
        }
        if (appUrl.endsWith('/')) {
            appUrl = appUrl.substring(0, appUrl.length - 1);
        }
        const output = BOOTSTRAP_TEMPLATE({ appUrl: appUrl });
        (0, utils_1.writeFile)(`${this.projectPath}/bootstrap.js`, output);
    }
    generateAppStyles() {
        return this.projectService.getAppCss().then(response => {
            const styles = STYLE_TEMPLATE({
                styles: this.transformStyle(response)
            });
            (0, utils_1.writeFile)(`${this.projectPath}/app.style.js`, styles);
            if (profile_1.default.generateWeb) {
                return this.saveAppDesignStyles(this.generateDesignStyles(response));
            }
        });
    }
    generateThemeVariables() {
        return this.projectService.getAppThemeVariables().then(response => {
            (0, utils_1.writeFile)(`${this.projectPath}/app.theme.variables.js`, response);
        }, () => { });
    }
    getAllResources(dirPath = this.projectPath + '/assets/resources', pathPrefix = 'resources', arrayOfFiles = []) {
        if (fs_extra_1.default.existsSync(dirPath)) {
            fs_extra_1.default.readdirSync(dirPath).forEach((file) => {
                if (fs_extra_1.default.statSync(dirPath + "/" + file).isDirectory()) {
                    arrayOfFiles = this.getAllResources(dirPath + "/" + file, pathPrefix + '/' + file, arrayOfFiles);
                }
                else {
                    const ext = (0, lodash_1.last)(file.split('.'));
                    if (file.indexOf('@') < 0 && ALLOWED_RESOURCE_EXT.indexOf(ext || '') >= 0) {
                        arrayOfFiles.push(pathPrefix + "/" + file);
                    }
                }
            });
        }
        return arrayOfFiles;
    }
    generateFontConfig() {
        return this.projectService.getFontConfig().then(code => {
            (0, utils_1.writeFile)(`${this.projectPath}/font.config.js`, code);
        }).catch(() => { });
    }
    generateResourceResolver() {
        return Promise.resolve().then(() => {
            if (profile_1.default.copyResources) {
                return this.projectService.getResources().then(src => {
                    if (src) {
                        fs_extra_1.default.copySync(src, this.projectPath + '/assets/resources');
                    }
                });
            }
        }).then(() => {
            const resources = profile_1.default.copyResources ? this.getAllResources() : [];
            const content = RESOURCE_RESOLVER_TEMPLATE({
                resources: resources,
                path: '../../assets/'
            });
            (0, utils_1.writeFile)(`${this.projectPath}/src/resolve/resource.resolver.js`, content);
        });
    }
    generateLocaleResolver() {
        return Promise.resolve().then(() => {
            const resources = profile_1.default.copyResources ? this.getAllResources(this.projectPath + '/i18n', 'i18n') : [];
            const content = RESOURCE_RESOLVER_TEMPLATE({
                resources: resources,
                path: '../../'
            });
            (0, utils_1.writeFile)(`${this.projectPath}/src/resolve/locale.resolver.js`, content);
        });
    }
    copyi18nFiles() {
        if (profile_1.default.loadLocaleFromRemote) {
            return Promise.resolve();
        }
        return this.projectService.geti18NFiles().then(p => {
            if (p) {
                fs_extra_1.default.copySync(p, this.projectPath + '/i18n');
            }
        });
    }
    generatePagesAndPartials() {
        let pageConfigs = null;
        return this.projectService.getPageConfigs().then(_pageConfigs => {
            pageConfigs = _pageConfigs;
            const pageCreationPromises = pageConfigs.map(p => {
                if (p.type === 'PAGE') {
                    return this.generatePageComponent(p.name);
                }
                if (this.isPartial(p.type)) {
                    return this.generatePartialComponent(p.name);
                }
            });
            return Promise.all(pageCreationPromises);
        })
            .then(() => this.generatePageConfig(pageConfigs))
            .then(() => this.generatePartialConfig(pageConfigs));
    }
    async mergePackageJson() {
        let packageToOveride = fs_extra_1.default.readJSONSync(`${this.projectPath}/package.json`, { encoding: 'utf-8' });
        if (profile_1.default.generateWeb) {
            const webPackageJson = fs_extra_1.default.readJSONSync(`${__dirname}/templates/package.web.json`, { encoding: 'utf-8' });
            packageToOveride = (0, lodash_1.merge)(packageToOveride, webPackageJson);
        }
        const packageOverride = await this.projectService.getPackageJSONOverride();
        if (packageOverride) {
            const packageOverriden = (0, lodash_1.merge)(packageToOveride, packageOverride);
            fs_extra_1.default.writeFileSync(`${this.projectPath}/package.json`, JSON.stringify(packageOverriden, null, 4));
        }
    }
    addCustomPluginsToPackageJson() {
        const config = fs_extra_1.default.readJsonSync(`${this.projectPath}/wm_rn_config.json`, {
            encoding: 'utf8'
        });
        let plugins = config.plugins;
        let data = fs_extra_1.default.readFileSync(`${this.projectPath}/package.json`, 'utf-8');
        const jsonData = JSON.parse(data);
        plugins.forEach((p) => {
            jsonData['dependencies'][p.name] = p.spec;
        });
        fs_extra_1.default.writeFileSync(`${this.projectPath}/package.json`, JSON.stringify(jsonData, null, 4));
    }
    async copyTheme() {
        if (!this.isPrefabApp) {
            return this.projectService.getTheme().then(p => {
                if (p) {
                    fs_extra_1.default.copySync(p, this.projectPath + '/theme');
                }
            });
        }
        return Promise.resolve();
    }
    generateApp() {
        fs_extra_1.default.copySync(__dirname + '/templates/project', this.projectPath);
        return this.generatePagesAndPartials()
            .then(() => this.generateResourceResolver())
            .then(() => this.generateAppScript())
            .then(() => this.generateAppStyles())
            .then(() => this.generateThemeVariables())
            .then(() => this.generateAppVariables())
            .then(() => this.generateFontConfig())
            .then(() => this.generateRNConfig())
            .then(() => this.generateBootstrapScript())
            .then(() => this.copyTheme())
            .then(() => this.copyi18nFiles())
            .then(() => this.generateLocaleResolver())
            .then(() => this.prepareDeviceOperationLoader())
            .then(() => this.addCustomPluginsToPackageJson())
            .then(() => this.prettify())
            .then(() => this.mergePackageJson())
            .then(() => this.projectService.copyNpmPackages(this.projectPath))
            .then(() => console.log('code generated at ' + this.projectPath));
    }
    generateFragment(name) {
        let pageConfigs = null;
        return this.projectService.getPageConfigs().then(_pageConfigs => {
            pageConfigs = _pageConfigs;
            const info = pageConfigs.find((config) => config.name === name);
            if (info) {
                if (info.type === 'PAGE') {
                    return this.generatePageComponent(info.name);
                }
                if (this.isPartial(info.type)) {
                    return this.generatePartialComponent(name);
                }
            }
        })
            .then(() => this.generatePageConfig(pageConfigs))
            .then(() => this.generatePartialConfig(pageConfigs))
            .then(() => this.prettify(`**/${name}/**/*.js`))
            .then(() => console.log('code generated at ' + this.projectPath));
    }
    ;
}
exports.default = AppGenerator;
//# sourceMappingURL=app.generator.js.map