"use strict";

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

var _debug = _interopRequireDefault(require("debug"));

var _path = require("path");

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

var _usageHelpers = require("./usage-helpers");

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());
  });
};

const strings = (0, _core.i18n)('plugin-bash-like');
const debug = (0, _debug.default)('plugins/bash-like/cmds/open');
/** Important for alignment to the Editor view component */

function contentTypeOf(suffix) {
  switch (suffix) {
    case 'sh':
      return 'shell';

    case 'md':
      return 'text/markdown';

    case 'html':
      return 'text/html';

    case 'yaml':
    case 'json':
      return suffix;

    default:
      return 'text/plain';
  }
}
/**
 * Decide how to display a given filepath
 *
 */


function open({
  argvNoOptions,
  REPL
}) {
  return __awaiter(this, void 0, void 0, function* () {
    const filepath = argvNoOptions[argvNoOptions.indexOf('open') + 1];
    debug('open', filepath);
    const fullpath = (0, _core.findFile)((0, _core.expandHomeDir)(filepath));
    const suffix = filepath.substring(filepath.lastIndexOf('.') + 1);

    if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg' || suffix === 'tiff' || suffix === 'tif' || suffix === 'gif' || suffix === 'icns' || suffix === 'ico' || suffix === 'webp' || suffix === 'bpg' || suffix === 'svg' || suffix === 'mov' || suffix === 'mp4' || suffix === 'ogg' || suffix === 'mp3') {
      // open binary/imag fields in a separate window
      window.open(fullpath, 'target=_blank');
      return true;
    } else if (suffix === 'pkl' || suffix === 'sab') {
      throw new Error('Opening of binary files not supported');
    } else {
      // fetch the data:
      //   --with-data says give us the file contents
      //   --enoent-ok says don't fail if the file does not exist
      const stats = (yield REPL.rexec(`fstat ${REPL.encodeComponent(filepath)} --with-data --enoent-ok`)).content;

      if (stats.isDirectory) {
        debug('trying to open a directory; delegating to ls');
        return REPL.qexec(`ls ${REPL.encodeComponent(filepath)}`);
      } else {
        const enclosingDirectory = (0, _path.dirname)(filepath);
        const data = stats.data;
        const name = (0, _path.basename)(filepath);
        const packageName = enclosingDirectory === '.' ? undefined : enclosingDirectory;
        const mode = typeof data === 'string' ? {
          mode: 'view',
          label: strings('Edit'),
          contentType: contentTypeOf(suffix),
          content: data
        } : {
          mode: 'view',
          label: strings('View'),
          content: data
        };
        const response = {
          apiVersion: 'kui-shell/v1',
          kind: 'File',
          metadata: {
            name,
            namespace: packageName
          },
          modes: [mode],
          spec: {
            filepath,
            fullpath
          }
        };
        return response;
      }
    }
  });
}

const usage = {
  strict: 'open',
  command: 'open',
  title: strings('openUsageTitle'),
  header: strings('openUsageHeader'),
  optional: _usageHelpers.localFilepath
};
/**
 * Register command handlers
 *
 */

var _default = registrar => {
  registrar.listen('/open', open, {
    usage
  });
};

exports.default = _default;