"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.doKustomize = void 0;

var _path = require("path");

var _core = require("@kui-shell/core");

var _flags = _interopRequireDefault(require("./flags"));

var _fqn = require("./fqn");

var _exec = require("./exec");

var _commandPrefix = _interopRequireDefault(require("../command-prefix"));

var _help = require("../../lib/util/help");

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

/*
 * Copyright 2019 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

const strings = (0, _core.i18n)('plugin-kubectl', 'kustomize');

function groupByKind(resources, rawFull) {
  const rawSplit = rawFull.split(/---/);
  const groups = resources.reduce((groups, resource, idx) => {
    const key = (0, _fqn.kindPartOf)(resource);
    const group = groups[key];

    if (!group) {
      groups[key] = {
        label: key,
        items: []
      };
    }

    groups[key].items.push({
      mode: resource.metadata.name,
      content: rawSplit[idx].replace(/^\n/, ''),
      contentType: 'yaml'
    });
    return groups;
  }, {});
  const rawMenu = {
    label: strings('Raw Data'),
    items: [{
      mode: 'YAML',
      content: rawFull,
      contentType: 'yaml'
    }]
  };
  return Object.values(groups).concat([rawMenu]);
}

const doKustomize = (command = 'kubectl') => args => __awaiter(void 0, void 0, void 0, function* () {
  if ((0, _help.isUsage)(args)) {
    return (0, _help.doHelp)(command, args);
  } else {
    const [yaml, {
      safeLoadAll
    }] = yield Promise.all([(0, _exec.doExecWithStdout)(args, undefined, command), Promise.resolve().then(() => require('js-yaml'))]);

    try {
      const resources = safeLoadAll(yaml);
      const inputFile = (0, _path.resolve)(args.argvNoOptions[args.argvNoOptions.indexOf('kustomize') + 1]);
      return {
        apiVersion: 'kui-shell/v1',
        kind: 'NavResponse',
        breadcrumbs: [{
          label: 'kustomize'
        }, {
          label: (0, _path.basename)(inputFile),
          command: `open ${inputFile}`
        }],
        menus: groupByKind(resources, yaml)
      };
    } catch (err) {
      console.error('error preparing kustomize response', err);
      return yaml;
    }
  }
});

exports.doKustomize = doKustomize;

var _default = registrar => {
  registrar.listen(`/${_commandPrefix.default}/kubectl/kustomize`, doKustomize(), _flags.default);
  registrar.listen(`/${_commandPrefix.default}/k/kustomize`, doKustomize(), _flags.default);
};

exports.default = _default;