'use strict';

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _pathExists = require('path-exists');

var _pathExists2 = _interopRequireDefault(_pathExists);

var _crossSpawn = require('cross-spawn');

var _crossSpawn2 = _interopRequireDefault(_crossSpawn);

var _log = require('./util/log');

var _log2 = _interopRequireDefault(_log);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DEFAULT_DEPENDENCIES = {
    react: '15.4.2',
    'react-native': '0.42.3',
    'react-native-tizen-dotnet': '>=0.1.1'
    //for debug
    //'react-native-tizen': 'file:/Users/admin/Documents/reactDotNative/Github/rn-tizen-netcore-app/react-native-tizen/',
};

var DEFAULT_DEV_DEPENDENCIES = {
    'babel-jest': '20.0.3',
    'babel-preset-react-native': '2.1.0',
    'jest': '20.0.4',
    'react-test-renderer': '15.4.2'
};

module.exports = function () {
    var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(appPath, appName, verbose) {
        var cwd = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ' ';
        var ownPackageName, ownPath, useYarn, npmVersion, readmeExists, appPackagePath, appPackage, data, command, args, proc;
        return _regenerator2.default.wrap(function _callee$(_context) {
            while (1) {
                switch (_context.prev = _context.next) {
                    case 0:
                        ownPackageName = require('../package.json').name;
                        ownPath = _path2.default.join(appPath, 'node_modules', ownPackageName);
                        _context.next = 4;
                        return (0, _pathExists2.default)(_path2.default.join(appPath, 'yarn.lock'));

                    case 4:
                        useYarn = _context.sent;


                        if (!useYarn) {
                            npmVersion = _crossSpawn2.default.sync('npm', ['--version']).stdout.toString().trim();


                            if (npmVersion.startsWith('5')) {
                                console.log(_chalk2.default.yellow('\n*******************************************************************************\nERROR: npm 5 is not supported yet\n*******************************************************************************\n\nIt looks like you\'re using npm 5 which was recently released.\n\nCreate React Native App doesn\'t work with npm 5 yet, unfortunately. We\nrecommend using npm 4 or yarn until some bugs are resolved.\n\nYou can follow the known issues with npm 5 at:\nhttps://github.com/npm/npm/issues/16991\n\n*******************************************************************************\n'));
                                process.exit(1);
                            }
                        }

                        _context.next = 8;
                        return (0, _pathExists2.default)(_path2.default.join(appPath, 'README.md'));

                    case 8:
                        readmeExists = _context.sent;

                        if (!readmeExists) {
                            _context.next = 12;
                            break;
                        }

                        _context.next = 12;
                        return _fsExtra2.default.name(_path2.default.join(appPath, 'README.md'), _path2.default.join(appPath, 'README.md.bak'));

                    case 12:
                        appPackagePath = _path2.default.join(appPath, 'package.json');
                        _context.t0 = JSON;
                        _context.next = 16;
                        return _fsExtra2.default.readFile(appPackagePath);

                    case 16:
                        _context.t1 = _context.sent;
                        appPackage = _context.t0.parse.call(_context.t0, _context.t1);


                        appPackage.main = 'index.js';
                        appPackage.scripts = {
                            server: 'node node_modules/react-native/local-cli/cli.js start',
                            test: 'node node_modules/jest/bin/jest.js --watch',
                            package: 'react-native-tizen package',
                            bundle: 'react-native-tizen bundle',
                            //dotnet: 'react-native-tizen dotnet',
                            launch: 'react-native-tizen-dotnet launch $npm_package_config_tvip $npm_package_config_mode'
                            //packageDebug:'yarn bundle -- dev; yarn dotnet -- debug; yarn package',
                            //packageRelease: 'yarn bundle; yarn dotnet -- release; yarn package',
                        };

                        appPackage.jest = {};
                        appPackage.config = {
                            "tvip": "192.168.100.1",
                            "mode": "Release"
                        };

                        if (!appPackage.dependencies) {
                            appPackage.dependencies = {};
                        }

                        if (!appPackage.devDependencies) {
                            appPackage.devDependencies = {};
                        }

                        (0, _assign2.default)(appPackage.dependencies, DEFAULT_DEPENDENCIES);
                        (0, _assign2.default)(appPackage.devDependencies, DEFAULT_DEV_DEPENDENCIES);

                        //npm install
                        _context.next = 28;
                        return _fsExtra2.default.writeFile(appPackagePath, (0, _stringify2.default)(appPackage, null, 2));

                    case 28:
                        _context.next = 30;
                        return _fsExtra2.default.copy(_path2.default.join(ownPath, 'template'), appPath);

                    case 30:
                        _context.prev = 30;
                        _context.next = 33;
                        return _fsExtra2.default.rename(_path2.default.join(appPath, 'gitignore'), _path2.default.join(appPath, '.gitignore'));

                    case 33:
                        _context.next = 48;
                        break;

                    case 35:
                        _context.prev = 35;
                        _context.t2 = _context['catch'](30);

                        if (!(_context.t2.code === 'EEXIST')) {
                            _context.next = 47;
                            break;
                        }

                        _context.next = 40;
                        return _fsExtra2.default.readFile(_path2.default.join(appPath, 'gitignore'));

                    case 40:
                        data = _context.sent;
                        _context.next = 43;
                        return _fsExtra2.default.appendFile(_path2.default.join(appPath, '.gitignore'), data);

                    case 43:
                        _context.next = 45;
                        return _fsExtra2.default.unlink(_path2.default.join(appPath, 'gitignore'));

                    case 45:
                        _context.next = 48;
                        break;

                    case 47:
                        throw _context.t2;

                    case 48:

                        //run yarn or npm
                        command = '';
                        args = [];


                        if (useYarn) {
                            command = 'yarnpkg';
                        } else {
                            command = 'npm';
                            args = ['install', '--save'];

                            if (verbose) {
                                args.push('--verbose');
                            }
                        }

                        (0, _log2.default)('Installing dependencies using ' + command + '...');
                        (0, _log2.default)();

                        if (command === 'yarnpkg') {
                            command = 'yarn';
                        }

                        proc = (0, _crossSpawn2.default)(command, args, { stdio: 'inherit' });

                        proc.on('close', function (code) {
                            if (code !== 0) {
                                console.error('`' + command + ' ' + args.join(' ') + '` failed');
                                return;
                            }

                            var cdpath = void 0;
                            if (_path2.default.resolve(cwd, appName) === appPath) {
                                cdpath = appName;
                            } else {
                                cdpath = appPath;
                            }

                            (0, _log2.default)('\n            \nSuccess! Created ' + appName + ' at ' + appPath + '\n            ');

                            if (readmeExists) {
                                (0, _log2.default)('\n                \n' + _chalk2.default.yellow('You had a `README.md` file, we renamed it to `README.old.md`'));
                            }

                            (0, _log2.default)('Start Prepare Tizen dotnet Project....');

                            var tempArray = [appPath + '/Tizen/tizen-manifest.xml', appPath + '/index.tizen.js', appPath + '/Tizen/Program.cs'];
                            tempArray.forEach(function (file) {
                                replaceName(file, /react_native_template/g, appName);
                            });

                            //Change template Name to App Name
                            function replaceName(file, src, dst) {
                                var data = _fsExtra2.default.readFileSync(file, 'utf8');
                                var result = data.replace(src, dst);
                                //create hash code to tizen app id;
                                var hashVal = result.replace(/hash_val/g, randomCode());
                                _fsExtra2.default.writeFileSync(file, hashVal, 'utf8');
                            }

                            //return 
                            function randomCode() {
                                var str = "",
                                    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

                                // generate 8 random numbers  
                                for (var i = 0; i < 8; i++) {
                                    var pos = Math.round(Math.random() * (arr.length - 1));
                                    str += arr[pos];
                                }
                                return str;
                            }

                            //rename csproj file
                            var csFile = appPath + '/Tizen/react_native_template.csproj';
                            var newName = appPath + '/Tizen/' + appName + '.csproj';
                            _fsExtra2.default.rename(csFile, newName, function (err) {
                                if (err) throw err;
                            });

                            (0, _log2.default)();
                            (0, _log2.default)('Happy on Tizen dotnet!');
                        });

                    case 56:
                    case 'end':
                        return _context.stop();
                }
            }
        }, _callee, undefined, [[30, 35]]);
    }));

    return function (_x, _x2, _x3) {
        return _ref.apply(this, arguments);
    };
}();
//# sourceMappingURL=init.js.map