"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.Wizard = void 0;

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _Confirm = require("./popups/Confirm");

var _DangerousHTML = require("./DangerousHTML");

var Wizard =
/*#__PURE__*/
function (_React$Component) {
  (0, _inheritsLoose2.default)(Wizard, _React$Component);

  function Wizard(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this; // XXX: startSnapshotRecording

    _this.snapshotRecording = true;
    _this.state = {
      showSnapshotRestoreDialog: !!_this.getSnapshot(),
      currentStepIndex: 0,
      maxVisitedStepIndex: 0,
      errors: {}
    };

    _this.setCurrentStepIndex = function (index) {
      if (index >= _this.getSteps().length) {
        throw new RangeError('Current wizard step index ' + _this.state.currentStepIndex + ' is out of ranges - step not found');
      }

      _this.setState({
        currentStepIndex: index,
        maxVisitedStepIndex: Math.max(_this.state.maxVisitedStepIndex, index)
      });
    };

    _this.resetMaxVisitedStepIndex = function (index) {
      _this.setState({
        maxVisitedStepIndex: Number(index) || 0
      });
    };

    _this.goNext = function () {
      var nextStepIndex = _this.getEnabledSiblingStepIndex(1);

      if (nextStepIndex !== null) {
        _this.validateCurrentStep(function () {
          _this.setCurrentStepIndex(nextStepIndex);
        }, nextStepIndex);
      } else {
        // eslint-disable-next-line
        console.error('Wizard has not following enabled steps - can not go next');
      }
    };

    _this.goBack = function () {
      var prevStepIndex = _this.getEnabledSiblingStepIndex(-1);

      if (prevStepIndex !== null) {
        _this.validateCurrentStep(function () {
          _this.setCurrentStepIndex(prevStepIndex);
        }, prevStepIndex);
      } else {
        // eslint-disable-next-line
        console.error('Wizard has not previous enabled steps - can not go back');
      }
    }; // XXX: inconsistency return - null (see getStepIndexById -1)


    _this.getEnabledSiblingStepIndex = function (direction) {
      var targetStep = null;
      var targetStepIndex = _this.state.currentStepIndex + direction;

      var steps = _this.getSteps();

      while (!targetStep) {
        targetStep = steps[targetStepIndex];

        if (targetStep.props.disabled) {
          targetStepIndex += direction;
          targetStep = null;

          if (targetStepIndex > steps.length - 1 || targetStepIndex < 0) {
            targetStepIndex = null;
            break;
          }
        }
      }

      return targetStepIndex;
    };

    _this.goToStep = function (id) {
      // XXX: RangeError within render
      var stepIndex = _this.getStepIndexById(id);

      if (stepIndex === -1) {
        throw new RangeError('Wizard step [' + id + '] is not exists');
      }

      _this.validateCurrentStep(function () {
        _this.setCurrentStepIndex(stepIndex);
      }, stepIndex);
    };

    _this.isFirstStep = function (id) {
      return _this.getStepIndexById(id) === 0;
    };

    _this.isLastStep = function (id) {
      var stepIndex = _this.getStepIndexById(id);

      var lastStepIndex = _this.getSteps().length - 1;
      return stepIndex >= 0 && stepIndex === lastStepIndex;
    };

    _this.getCurrentStepIndex = function () {
      return _this.state.currentStepIndex;
    };

    _this.getMaxVisitedStepIndex = function () {
      return _this.state.maxVisitedStepIndex;
    };

    _this.stepOnLeaveHandlers = {};

    _this.addStepOnLeaveHandler = function (id, func) {
      _this.stepOnLeaveHandlers[id] = func;
    };

    return _this;
  }

  var _proto = Wizard.prototype;

  _proto.getChildContext = function getChildContext() {
    return {
      wizard: this
    };
  };

  _proto.componentDidUpdate = function componentDidUpdate() {
    if (!this.state.showSnapshotRestoreDialog) {
      this.saveSnapshot();
    }
  }
  /**
   * @abstract
   */
  ;

  _proto.getSnapshotKey = function getSnapshotKey() {
    return null;
  }
  /**
   * @abstract
   */
  ;

  _proto.getSnapshotValue = function getSnapshotValue() {
    return null;
  }
  /**
   * @abstract
   */
  ;

  _proto.restoreSnapshot = function restoreSnapshot() {};

  _proto.saveSnapshot = function saveSnapshot() {
    var key = this.getSnapshotKey();
    var value = this.getSnapshotValue();

    if (key && value && this.snapshotRecording) {
      if (window.localStorage) {
        window.localStorage.setItem(key, JSON.stringify(value));
      }
    }
  };

  _proto.getSnapshot = function getSnapshot() {
    var key = this.getSnapshotKey();
    return key && window.localStorage ? window.localStorage.getItem(this.getSnapshotKey()) : null;
  };

  _proto.getRestoreConfirmationText = function getRestoreConfirmationText() {
    return _react.default.createElement(_DangerousHTML.DangerousHTML, null, Wizard.confirmWizardRestore);
  };

  _proto.readSnapshot = function readSnapshot() {
    return JSON.parse(this.getSnapshot());
  };

  _proto.resetSnapshot = function resetSnapshot(stopRecording) {
    if (stopRecording === void 0) {
      stopRecording = true;
    }

    var key = this.getSnapshotKey();

    if (stopRecording) {
      this.stopSnapshotRecording();
    }

    return key && window.localStorage ? window.localStorage.removeItem(this.getSnapshotKey()) : null;
  };

  _proto.startSnapshotRecording = function startSnapshotRecording() {
    this.snapshotRecording = true;
  };

  _proto.stopSnapshotRecording = function stopSnapshotRecording() {
    this.snapshotRecording = false;
  };

  _proto.getSteps = function getSteps() {
    return [];
  };

  _proto.getStepIndexById = function getStepIndexById(id) {
    return this.getSteps().findIndex(function (step) {
      return step.props.id === id;
    });
  };

  _proto.validateCurrentStep = function validateCurrentStep(onSuccess, targetStepIndex) {
    var _this2 = this;

    var currentStep = this.getSteps()[this.state.currentStepIndex];
    var isValidationNeeded = targetStepIndex > this.state.currentStepIndex;

    var successHandler = function successHandler() {
      var stepOnLeaveHandler = _this2.stepOnLeaveHandlers[currentStep.props.id];

      if (stepOnLeaveHandler) {
        stepOnLeaveHandler().then(onSuccess.bind(_this2));
      } else {
        onSuccess.call(_this2);
      }
    };

    if (currentStep.props.validation && isValidationNeeded) {
      this.setState({
        errors: {}
      });
      currentStep.props.validation(this.state).then(successHandler).catch(function (errors) {
        _this2.setState({
          errors: errors
        });
      });
    } else {
      successHandler();
    }
  };

  _proto.render = function render() {
    var _this3 = this;

    if (this.state.showSnapshotRestoreDialog) {
      return _react.default.createElement(_Confirm.Confirm, {
        closeButton: false,
        noAutoClose: true,
        submitAction: function submitAction(e) {
          var snapshot = _this3.readSnapshot();

          _this3.restoreSnapshot(snapshot);

          _this3.setState({
            showSnapshotRestoreDialog: false
          });
        },
        cancelAction: function cancelAction(e) {
          return _this3.setState({
            showSnapshotRestoreDialog: false
          });
        }
      }, this.getRestoreConfirmationText());
    } else {
      return this.getSteps()[this.state.currentStepIndex];
    }
  };

  return Wizard;
}(_react.default.Component);

exports.Wizard = Wizard;
(0, _defineProperty2.default)(Wizard, "confirmWizardRestore", 'TRANSLATE:CONFIRM_WIZARD_RESTORE');
(0, _defineProperty2.default)(Wizard, "childContextTypes", {
  wizard: _propTypes.default.object
});