import { safeLoad } from 'js-yaml';
import { flatten, flattenDepth } from 'lodash';

var tryParseYAML = function tryParseYAML(text) {
  try {
    return safeLoad(text);
  } catch (e) {
    console.error(e);
    return {};
  }
};
/**
 * 旧アセット定義ファイル(YAML)を新仕様に変換する
 */


export default function convertAsset() {
  var definitionFileTexts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var configs = definitionFileTexts.map(tryParseYAML);
  var scopeNames = flatten(configs.map(function (def) {
    return Object.keys(def);
  }));
  var scopes = scopeNames.map(function (name) {
    return {
      name: name,
      defaultActiveCategory: -1
    };
  });

  var nullable = function nullable(value) {
    return value ? value + '' : null;
  };

  var converter = function converter() {
    var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    return function (config) {
      return {
        name: nullable(config.label),
        description: nullable(config.description),
        category: -1,
        iconUrl: nullable(config.image),
        insertCode: nullable(config.code),
        moduleCode: null,
        plan: 'free',
        variations: null,
        production: true,
        scopes: [scopeNames.indexOf(scope)],
        filePath: nullable(config.filePath) // 既にあるファイルのパス

      };
    };
  };

  var buttons = flattenDepth(configs.map(function (object) {
    return Object.keys(object).map(function (scope) {
      return object[scope].map(converter(scope));
    });
  }), 3);
  return {
    version: '',
    categories: [],
    scopes: scopes,
    module: {},
    buttons: buttons
  };
}