"use strict";

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

var _react = _interopRequireDefault(require("react"));

var _uuid = require("uuid");

var _path = require("path");

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

var _fetch = _interopRequireDefault(require("./fetch"));

var _commentary = require("./commentary");

var _frontmatterParser = require("../components/Content/Markdown/frontmatter-parser");

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

/*
 * Copyright 2022 The Kubernetes Authors
 *
 * 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 response(filepath, {
  data,
  codeBlockResponses
}) {
  return {
    apiVersion: 'kui-shell/v1',
    kind: 'CommentaryResponse',
    props: {
      filepath,
      children: data,
      codeBlockResponses
    }
  };
}

function show(args) {
  return __awaiter(this, void 0, void 0, function* () {
    const filepath = args.argvNoOptions[1];

    if (!args.parsedOptions.here) {
      yield args.REPL.qexec(`tab new --cmdline "show --here ${(0, _core.encodeComponent)(filepath)}"`);
      return true;
    }

    (0, _commentary.setTabReadonly)(args);
    return response(filepath, yield (0, _fetch.default)(filepath, args));
  });
}

function guide(args) {
  return __awaiter(this, void 0, void 0, function* () {
    try {
      const filepath = args.argvNoOptions[1];

      if (!args.parsedOptions.here && !(0, _core.isPopup)()) {
        yield args.REPL.qexec(`tab new --cmdline "guide --here ${(0, _core.encodeComponent)(filepath)}"`);
        return true;
      }

      const reader = file => __awaiter(this, void 0, void 0, function* () {
        const {
          data
        } = yield (0, _fetch.default)(file.path, args);
        file.value = data;
        return file;
      });

      const {
        data: rawData
        /* , codeBlockResponses */

      } = yield (0, _fetch.default)(filepath, args);
      const {
        attributes
      } = (0, _frontmatterParser.tryFrontmatter)(rawData);
      const {
        VFile
      } = yield Promise.resolve().then(() => require('vfile'));
      const {
        Choices,
        Parser
      } = yield Promise.resolve().then(() => require('madwizard'));
      const input = new VFile({
        value: rawData,
        cwd: _core.Util.cwd(),
        path: _core.Util.expandHomeDir(filepath)
      });
      const choices = Choices.newChoiceState('default');
      const {
        blocks
      } = yield Parser.blockify(input, reader, choices);
      const {
        default: Guide
      } = yield Promise.resolve().then(() => require('../components/Content/Markdown/components/guide'));
      const {
        default: Imports
      } = yield Promise.resolve().then(() => require('../components/Content/Markdown/components/Imports'));
      const {
        default: SplitInjector
      } = yield Promise.resolve().then(() => require('../components/Views/Terminal/SplitInjector'));
      const title = attributes.title || (0, _path.basename)(filepath);
      const {
        execUUID: uuid
      } = args.execOptions;

      const tree = _react.default.createElement(Imports, {
        imports: blocks,
        choices,
        title
      });

      const guide = _react.default.createElement(Guide, {
        tab: args.tab,
        uuid,
        blocks,
        choices,
        title
      });

      const react = _react.default.createElement(SplitInjector.Consumer, undefined, injector => {
        injector.inject([{
          uuid: (0, _uuid.v4)(),
          node: tree,
          position: 'left-strip',
          count: 0,
          opts: {
            inverseColors: true
          }
        }]);
        return injector.modify(args.tab.uuid, guide, {
          maximized: true
        });
      });

      args.tab.setTitle(title);
      (0, _commentary.setTabReadonly)(args);
      return {
        react
      };
    } catch (err) {
      console.error(err);
      throw err;
    }
    /* const data = `---
    title: ${attributes.title || basename(filepath)}
    layout:
      1: left
      2:
          position: default
          maximized: true
      - ${Util.expandHomeDir(filepath)}
    ---
         ::imports
         ---
         ::guide
    `
           setTabReadonly(args)
    return response(filepath, {
      data,
      codeBlockResponses
    }) */

  });
}
/**
 * This plugin introduces the commentary command
 *
 */


function registerGuideController(commandTree) {
  const flags = {
    boolean: ['here']
  };
  commandTree.listen('/show', show, {
    outputOnly: true,
    flags
  });
  commandTree.listen('/guide', guide, {
    outputOnly: true,
    flags
  });
}