"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _i18n = require("@kui-shell/core/mdist/api/i18n");
var _madwizard = require("madwizard");
var _Progress = _interopRequireDefault(require("./Progress"));
var _Card = _interopRequireDefault(require("../../../../spi/Card"));
var _Loading = _interopRequireDefault(require("../../../../spi/Loading"));
var _ProgressStepper = require("../../../ProgressStepper");
var _MiniProgressStepper = require("../../../MiniProgressStepper");
var _LinkStatus = require("../../../LinkStatus");
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());
  });
};
const KWizard = _react.default.lazy(() => Promise.resolve().then(() => require('./KWizard')));
const strings = (0, _i18n.i18n)('plugin-client-common', 'code');
class Wizard extends _react.default.PureComponent {
  constructor(props) {
    super(props);
    this.cleaners = [];
    this._statusUpdateHandler = (statusVector, codeBlockId) => {
      const status = (0, _ProgressStepper.statusFromStatusVector)(statusVector, false);
      this.updateStatus(codeBlockId, status);
    };
    this.memos = new _madwizard.Memoizer();
    this.state = {
      graph: undefined,
      status: undefined,
      codeBlocksPerStep: undefined
    };
  }
  init(props) {
    return __awaiter(this, void 0, void 0, function* () {
      const codeBlocks = yield Promise.all(Wizard.children(props).map(_ => _madwizard.Graph.compile(Wizard.containedCodeBlocks(_), props.choices, this.memos)));
      this.setState(state => {
        const status = state.status || {};
        const codeBlocksPerStep = codeBlocks.map(codeBlocksInStep => _madwizard.Graph.blocks(codeBlocksInStep, props.choices).map(_ => ({
          codeBlockId: _.id,
          validate: _.validate,
          body: _.body,
          language: _.language,
          optional: _.optional,
          status: status[_.id]
        })));
        const noChangeToCodeBlocks = state && Wizard.sameCodeBlocks(state.codeBlocksPerStep, codeBlocksPerStep);
        return {
          status,
          codeBlocksPerStep: noChangeToCodeBlocks ? state.codeBlocksPerStep : codeBlocksPerStep,
          graph: noChangeToCodeBlocks ? state.graph : _madwizard.Graph.order(_madwizard.Graph.sequence(codeBlocks.filter(Boolean)))
        };
      });
    });
  }
  static sameCodeBlock(a, b) {
    return a.codeBlockId === b.codeBlockId && a.validate === b.validate && a.body === b.body && a.language === b.language && a.optional === b.optional && a.status === b.status;
  }
  static sameCodeBlocks(AA, BB) {
    return AA && BB && AA.every((A, idx1) => A.every((a, idx2) => Wizard.sameCodeBlock(a, BB[idx1][idx2])));
  }
  componentDidMount() {
    this.init(this.props);
    _madwizard.Graph.blocks(this.state.graph, 'all').forEach(_ => {
      (0, _LinkStatus.subscribeToLinkUpdates)(_.id, this._statusUpdateHandler);
      this.cleaners.push(() => (0, _LinkStatus.unsubscribeToLinkUpdates)(_.id, this._statusUpdateHandler));
    });
  }
  componentWillUnmount() {
    this.cleaners.forEach(_ => _());
  }
  updateStatus(codeBlockId, status) {
    this.setState(curState => {
      if (curState.status[codeBlockId] === status) {
        // no change to state!
        return null;
      } else {
        curState.status[codeBlockId] = status;
        return {
          status: Object.assign({}, curState.status)
        };
      }
    });
  }
  wizardCodeBlockSteps(stepIdx) {
    const containedCodeBlocks = this.state.codeBlocksPerStep[stepIdx];
    return containedCodeBlocks && containedCodeBlocks.length > 0 && _react.default.createElement(_MiniProgressStepper.MiniProgressStepper, {
      steps: containedCodeBlocks
    });
  }
  wizardStepDescription(stepIdx, description) {
    return _react.default.createElement("div", {
      className: "kui--wizard-nav-item-description"
    }, this.wizardCodeBlockSteps(stepIdx), _react.default.createElement("div", {
      className: "paragraph"
    }, description));
  }
  static containedCodeBlocks(_) {
    if (typeof _.props.containedCodeBlocks === 'string' && _.props.containedCodeBlocks.length > 0) {
      return _.props.containedCodeBlocks.split(' ').filter(Boolean).map(_ => JSON.parse(Buffer.from(_, 'base64').toString()));
    } else {
      return undefined;
    }
  }
  /** Overall progress across all steps */
  progress() {
    if (this.props['data-kui-wizard-progress'] === 'bar' && _madwizard.Graph.blocks(this.state.graph).length > 0) {
      return _react.default.createElement("div", {
        className: "kui--markdown-major-paragraph"
      }, _react.default.createElement(_Progress.default, {
        status: this.state.status,
        choices: this.props.choices,
        codeBlocks: this.state.graph,
        title: strings('Completed tasks')
      }));
    }
  }
  static children(props) {
    return (props.children || []).slice(1);
  }
  wizard() {
    const steps = Wizard.children(this.props).map((_, stepIdx) => ({
      name: _.props['data-kui-title'],
      hideCancelButton: true,
      stepNavItemProps: {
        children: this.wizardStepDescription(stepIdx, _.props['data-kui-description'])
      },
      component: _react.default.createElement(_Card.default, {
        className: "kui--markdown-tab-card"
      }, _.props && _.props.children)
    }));
    // onGoToStep={this._onWizardStepChange} onNext={this._onWizardStepChange} onBack={this._onWizardStepChange}
    const description = this.props.children[0];
    return _react.default.createElement(KWizard, {
      title: this.props['data-kui-title'],
      description: _react.default.isValidElement(description) && description,
      descriptionFooter: this.progress(),
      steps: steps
    });
  }
  render() {
    if (!this.state.graph) {
      return _react.default.createElement(_Loading.default, null);
    } else {
      return this.wizard();
    }
  }
}
/* private readonly _onWizardStepChange = (newStep: { name: React.ReactNode }) => {
    if (typeof newStep.name === 'string') {
      const activeKey = this.props.children.findIndex(_ => _.props.title === newStep.name)
      if (activeKey >= 0) {
        this.setState({ activeKey })
      }
    }
  } */
exports.default = Wizard;