"use strict";

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

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

var _fetchFile = require("../lib/util/fetch-file");

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

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

function isFile(filepath) {
  return __awaiter(this, void 0, void 0, function* () {
    const {
      lstat
    } = yield Promise.resolve().then(() => require('fs'));
    return new Promise((resolve, reject) => {
      lstat(filepath, (err, stats) => {
        if (err) {
          if (err.code === 'ENOENT') {
            resolve(false);
          } else {
            reject(err);
          }
        } else {
          resolve(stats.isFile());
        }
      });
    });
  });
}

function fetchKustomizeString(repl, uri) {
  return __awaiter(this, void 0, void 0, function* () {
    const [isFile0, {
      join
    }] = yield Promise.all([isFile(uri), Promise.resolve().then(() => require('path'))]);

    if (isFile0) {
      return {
        data: yield (0, _fetchFile.fetchFileString)(repl, uri)[0]
      };
    } else {
      const k1 = join(uri, 'kustomization.yml');
      const k2 = join(uri, 'kustomization.yaml');
      const k3 = join(uri, 'Kustomization');
      const [isFile1, isFile2, isFile3] = yield Promise.all([isFile(k1), isFile(k2), isFile(k3)]);
      const dir = uri; // if we are here, then `uri` is a directory

      if (isFile1) {
        return {
          data: (yield (0, _fetchFile.fetchFileString)(repl, k1))[0],
          dir
        };
      } else if (isFile2) {
        return {
          data: (yield (0, _fetchFile.fetchFileString)(repl, k2))[0],
          dir
        };
      } else if (isFile3) {
        return {
          data: (yield (0, _fetchFile.fetchFileString)(repl, k3))[0],
          dir
        };
      }
    }
  });
}
/**
 * A server-side shim to allow browser-based clients to fetch `-f`
 * file content.
 *
 */


var _default = registrar => {
  registrar.listen(`/${_commandPrefix.default}/_fetchfile`, ({
    argvNoOptions,
    parsedOptions,
    REPL
  }) => __awaiter(void 0, void 0, void 0, function* () {
    const uri = argvNoOptions[argvNoOptions.indexOf('_fetchfile') + 1];

    if (!parsedOptions.kustomize) {
      return (0, _fetchFile.fetchFileString)(REPL, uri);
    } else {
      return {
        mode: 'raw',
        content: yield fetchKustomizeString(REPL, uri)
      };
    }
  }), {
    requiresLocal: true,
    flags: {
      boolean: ['kustomize']
    }
  });
};

exports.default = _default;