"use strict";

var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

_Object$defineProperty(exports, "__esModule", {
  value: true
});

exports.default = void 0;

var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));

var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));

var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _child_process = require("child_process");

var _plugin = _interopRequireDefault(require("@start/plugin"));

var _default = theme => (0, _plugin.default)('MERGE THEME', ({
  reporter
}) => /*#__PURE__*/(0, _asyncToGenerator2.default)(function* () {
  if (!theme) {
    reporter.emit('message', 'No theme found, skipping step');
    return;
  } else {
    reporter.emit('message', 'Theme ' + theme + ' found');
  }

  const newTheme = 'theme-' + theme;

  try {
    return new _promise.default((resolve, reject) => {
      const deleteDirectory = dir => {
        try {
          _fs.default.rmdirSync(dir, {
            recursive: true
          });
        } catch (err) {
          reporter.emit(`Error while deleting ${dir}.`);
        }
      };

      const copyFolderSync = (from, to) => {
        var _context;

        _fs.default.mkdirSync(to);

        (0, _forEach.default)(_context = _fs.default.readdirSync(from)).call(_context, element => {
          if (_fs.default.lstatSync(_path.default.join(from, element)).isFile()) {
            _fs.default.copyFileSync(_path.default.join(from, element), _path.default.join(to, element));
          } else {
            copyFolderSync(_path.default.join(from, element), _path.default.join(to, element));
          }
        });
      };

      const directoryExists = directory => {
        try {
          if (_fs.default.existsSync(directory)) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          return false;
        }
      };

      const copyConfigsAndWriteLessfiles = themeFolder => {
        //first copy configs
        const workingDirectory = process.cwd();

        const themeConfigs = _path.default.join(themeFolder, 'configs');

        const appConfigs = _path.default.join(workingDirectory, 'app/configs');

        if (directoryExists(themeConfigs) && directoryExists(appConfigs)) {
          const themeFolderInApp = _path.default.join(appConfigs, 'theme');

          if (directoryExists(themeFolderInApp)) {
            //cleanup
            deleteDirectory(themeFolderInApp);
          }

          copyFolderSync(themeConfigs, _path.default.join(appConfigs, 'theme'));
        } else {
          reporter.emit('No configs folder in theme or app -- skipping');
        } //then write less files


        const appLess = '@import "~' + newTheme + '/styles/base.less";';

        _fs.default.writeFile('./app/assets/styles/App.less', appLess, 'utf-8', /*#__PURE__*/function () {
          var _ref2 = (0, _asyncToGenerator2.default)(function* (err, result) {
            if (!!err) reject(err);
            const fontLess = '@import "~' + newTheme + '/styles/fonts/fonts.less";';

            _fs.default.writeFile('./app/assets/styles/Fonts.less', fontLess, 'utf-8', /*#__PURE__*/function () {
              var _ref3 = (0, _asyncToGenerator2.default)(function* (err, result) {
                if (!!err) reject(err);
                return resolve();
              });

              return function (_x3, _x4) {
                return _ref3.apply(this, arguments);
              };
            }());
          });

          return function (_x, _x2) {
            return _ref2.apply(this, arguments);
          };
        }());
      };

      _fs.default.readFile('./package.json', 'utf-8', /*#__PURE__*/function () {
        var _ref4 = (0, _asyncToGenerator2.default)(function* (err, data) {
          if (!!err) reject(err);
          const packageJson = JSON.parse(data);
          let themeAlreadyInstalled = false;

          for (const prop in packageJson.dependencies) {
            if ((0, _startsWith.default)(prop).call(prop, newTheme)) {
              themeAlreadyInstalled = true;
            }
          }

          const workingDirectory = process.cwd();
          const packageFolder = '../../packages';

          const themeFolder = _path.default.join(workingDirectory, packageFolder, newTheme);

          if (themeAlreadyInstalled) {
            reporter.emit('Theme is already installed');
            copyConfigsAndWriteLessfiles(themeFolder);
          } else {
            const yarnCommand = `yarn add file:${themeFolder}`;
            (0, _child_process.exec)(yarnCommand, err => {
              if (!!err) reject(err);
              copyConfigsAndWriteLessfiles(themeFolder);
            });
          }
        });

        return function (_x5, _x6) {
          return _ref4.apply(this, arguments);
        };
      }());
    });
  } catch (e) {
    return _promise.default.reject(e);
  }
}));

exports.default = _default;
module.exports = exports.default;