"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.commandWithoutResource = exports.getCommandFromArgs = exports.NotFoundError = exports.TryLaterError = exports.StatusError = exports.toOpenWhiskFQN = exports.isDirectory = exports.maybeAsDate = void 0;

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

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

/*
 * Copyright 2018 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());
  });
};

/**
 * If the given string is a Date, then return it in local time
 *
 */
const maybeAsDate = str => {
  try {
    const localized = new Date(str).toLocaleString();

    if (localized === 'Invalid Date') {
      // oh well!
      return str;
    } else {
      return localized;
    }
  } catch (err) {
    // oh well!
    return str;
  }
};
/**
 * Is the given filepath a directory?
 *
 */


exports.maybeAsDate = maybeAsDate;

const isDirectory = filepath => // eslint-disable-next-line no-async-promise-executor
new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
  const {
    inBrowser
  } = yield Promise.resolve().then(() => require('@kui-shell/core'));

  if (inBrowser()) {
    resolve(false);
  } else {
    // why the dynamic import? being browser friendly here
    const {
      lstat
    } = yield Promise.resolve().then(() => require('fs'));
    lstat(filepath, (err, stats) => {
      if (err) {
        if (err.code === 'ENOENT') {
          resolve(undefined);
        } else {
          reject(err);
        }
      } else {
        resolve(stats.isDirectory());
      }
    });
  }
}));
/**
 * Turn a resource object into an OpenWhisk fully qualified name. This
 * assumes that resources have been "spread" so that there is one
 * OpenWhisk asset per spec.
 *
 */


exports.isDirectory = isDirectory;

const toOpenWhiskFQN = ({
  kind,
  spec,
  metadata
}) => {
  if (kind === 'Function' || kind === 'Composition') {
    // FunctionSpec
    const actionName = spec.name || metadata.name;
    const packageName = spec.package;
    return {
      type: kind === 'Function' ? 'action' : 'app',
      packageName,
      actionName,
      fqn: packageName ? `${packageName}/${actionName}` : actionName
    };
  } else if (kind === 'Composition') {
    return {
      type: 'app',
      fqn: metadata.name
    };
  } else if (kind === 'Package' || kind === 'Rule' || kind === 'Trigger') {
    return {
      type: kind.toLowerCase(),
      fqn: metadata.name
    };
  } else {
    return {
      type: 'unknown',
      fqn: metadata.name
    };
  }
};

exports.toOpenWhiskFQN = toOpenWhiskFQN;

class StatusError extends Error {}

exports.StatusError = StatusError;

class TryLaterError extends StatusError {}

exports.TryLaterError = TryLaterError;

class NotFoundError extends StatusError {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  constructor(message, code = 404) {
    super(message);
    this.code = code;
  }

}

exports.NotFoundError = NotFoundError;

const getCommandFromArgs = args => {
  return args.argvNoOptions[0] === _commandPrefix.default ? args.argvNoOptions[1] : args.argvNoOptions[0];
};
/**
 * Check if the command has verb but not resource. e.g. kubectl get
 * This is a special case since kubectl returns error instead of usage
 *
 */


exports.getCommandFromArgs = getCommandFromArgs;

const commandWithoutResource = args => {
  if (args.argvNoOptions[0] === _commandPrefix.default) {
    return args.argvNoOptions.length === 3;
  } else {
    return args.argvNoOptions.length === 2;
  }
};

exports.commandWithoutResource = commandWithoutResource;