'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports['default'] = getDashBoardPath;

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _nunjucks = require('nunjucks');

var _nunjucks2 = _interopRequireDefault(_nunjucks);

var _glob = require('glob');

var _glob2 = _interopRequireDefault(_glob);

var _isArray = require('lodash/isArray');

var _isArray2 = _interopRequireDefault(_isArray);

var _isObject = require('lodash/isObject');

var _isObject2 = _interopRequireDefault(_isObject);

var _context = require('./context');

var _context2 = _interopRequireDefault(_context);

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

var dashboardTemplate = _fs2['default'].readFileSync(_path2['default'].join(__dirname, '../../nunjucks/dashboard.nunjucks.js')).toString();

function normalizeDashBoardComponentOrLocale(components, key, dir) {
  _glob2['default'].sync(_path2['default'].join(process.cwd(), dir)).forEach(function (match) {
    components.push('"' + key + '/' + _path2['default'].basename(match, _path2['default'].extname(match)) + '": function() { return import("' + match + '"); },');
  });
}

function getDashBoards(dashboard) {
  var dashboardComponents = [];
  var dashboardLocale = [];
  if ((0, _isObject2['default'])(dashboard)) {
    Object.keys(dashboard).forEach(function (key) {
      var value = dashboard[key];
      var componentsPath = value;
      var localePath = void 0;
      if ((0, _isObject2['default'])(value)) {
        componentsPath = value.components;
        localePath = value.locale;
      }
      if (typeof componentsPath === 'string') {
        normalizeDashBoardComponentOrLocale(dashboardComponents, key, componentsPath);
      } else if ((0, _isArray2['default'])(componentsPath)) {
        componentsPath.forEach(function (dir) {
          normalizeDashBoardComponentOrLocale(dashboardComponents, key, dir);
        });
      }
      if (typeof localePath === 'string') {
        normalizeDashBoardComponentOrLocale(dashboardLocale, key, localePath);
      }
    });
  }
  return '\n{\n  dashboardComponents: {\n    ' + dashboardComponents.join('\n    ') + '\n  },\n  dashboardLocale: {\n    ' + dashboardLocale.join('\n    ') + '\n  }\n}\n  ';
}

function getDashBoardPath(configEntryName) {
  var dashboard = _context2['default'].choerodonConfig.dashboard,
      tmpDirPath = _context2['default'].tmpDirPath;

  var dashboardPath = _path2['default'].join(tmpDirPath, 'dashboard.' + configEntryName + '.js');
  _nunjucks2['default'].configure(dashboardPath, {
    autoescape: false
  });
  _fs2['default'].writeFileSync(dashboardPath, _nunjucks2['default'].renderString(dashboardTemplate, {
    dashboard: getDashBoards(dashboard)
  }));
  return dashboardPath;
}