"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.versionOf = versionOf;
exports.kindPart = kindPart;
exports.kindPartOf = kindPartOf;
exports.kindAndNamespaceOf = kindAndNamespaceOf;
exports.fqn = fqn;
exports.fqnOf = fqnOf;
exports.fqnOfRef = fqnOfRef;
exports.default = void 0;

/*
 * Copyright 2019-2020 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.
 */

/**
 * Extract the group and version from an `apiVersion` string
 *
 */
function versionOf(apiVersion) {
  const [group, version] = apiVersion.split('/');

  if (!version) {
    // e.g. 'v1' which has no group part; here, kubectl does not
    // accept queries of the form Pod.v1; so we just drop the
    // apiVersion part from the query.
    // Hypothesis: kind.version doesn't work
    return {
      group: '',
      version: ''
    };
  } else {
    // e.g. 'tekton.dev/v1alpha1' which is of the form 'group/version'
    // turn this into .version.group, so that a query can be made of
    // the form kind.version.group
    return {
      group,
      version
    };
  }
}

function versionString(apiVersion) {
  const {
    group,
    version
  } = versionOf(apiVersion);
  return group.length > 0 ? `.${version}.${group}` : '';
}

function kindPart(apiVersion, kind) {
  return `${kind}${versionString(apiVersion)}`;
}

function kindPartOf(resource) {
  return kindPart(resource.apiVersion, resource.kind);
}

function kindAndNamespaceOf(resource) {
  return `${kindPartOf(resource)} -n ${resource.metadata.namespace}`;
}

function fqn(apiVersion, kind, name, namespace) {
  if (kind === 'Namespace' && apiVersion === 'v1') {
    return `${kind} ${name}`;
  } else {
    return `${kindPart(apiVersion, kind)} ${namespace === '<none>' ? '' : `-n ${namespace}`} ${name}`;
  }
}

function fqnOf(resource) {
  return fqn(resource.apiVersion, resource.kind, resource.metadata.name, resource.metadata.namespace);
}

function fqnOfRef({
  group,
  version,
  kind,
  name,
  namespace
}) {
  return `${kind}${group ? `.${version}.${group}` : ''} ${namespace === '<none>' ? '' : `-n ${namespace}`} ${name}`;
}

var _default = fqn;
exports.default = _default;