"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

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

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

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

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

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

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

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

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

var _styles = require("@material-ui/core/styles");

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

var color = _interopRequireWildcard(require("./color"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

//Used these below to replace \\embed{newLine} with \\newline from prompt which will get parsed in MathJax
var NEWLINE_BLOCK_REGEX = /\\embed\{newLine\}\[\]/g;
var NEWLINE_LATEX = '\\newline ';

var PreviewPrompt = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(PreviewPrompt, _Component);

  var _super = _createSuper(PreviewPrompt);

  function PreviewPrompt() {
    var _this;

    (0, _classCallCheck2["default"])(this, PreviewPrompt);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "parsedText", function (text) {
      var customAudioButton = _this.props.customAudioButton;
      var div = document.createElement('div');
      div.innerHTML = text;
      var audio = div.querySelector('audio');

      if (audio) {
        var source = document.createElement('source');
        source.setAttribute('type', 'audio/mp3');
        source.setAttribute('src', audio.getAttribute('src'));
        audio.removeAttribute('src');
        audio.setAttribute('id', 'pie-prompt-audio-player');
        audio.appendChild(source);

        if (customAudioButton) {
          audio.style.display = 'none';
          var playButton = document.createElement('div');
          playButton.id = 'play-audio-button';
          Object.assign(playButton.style, {
            cursor: 'pointer',
            display: 'block',
            width: '128px',
            height: '128px',
            backgroundImage: "url(".concat(customAudioButton.pauseImage, ")"),
            backgroundSize: 'cover',
            borderRadius: '50%',
            border: '1px solid #326295'
          });
          audio.parentNode.insertBefore(playButton, audio);
        }
      }

      return div.innerHTML;
    });
    return _this;
  }

  (0, _createClass2["default"])(PreviewPrompt, [{
    key: "addCustomAudioButtonControls",
    value: function addCustomAudioButtonControls() {
      var _this$props = this.props,
          autoplayAudioEnabled = _this$props.autoplayAudioEnabled,
          customAudioButton = _this$props.customAudioButton;
      var playButton = document.getElementById('play-audio-button');
      var audio = document.getElementById('pie-prompt-audio-player');

      if (autoplayAudioEnabled && audio) {
        audio.play().then(function () {
          if (playButton && customAudioButton) {
            audio.addEventListener('ended', handleAudioEnded);
          }
        })["catch"](function (error) {
          console.error('Error playing audio', error);
        });
      }

      if (!playButton || !audio || !customAudioButton) return;

      var handlePlayClick = function handlePlayClick() {
        // if already playing, don't play again
        if (!audio.paused) return;
        if (playButton.style.backgroundImage.includes(customAudioButton.pauseImage)) return;
        audio.play();
      };

      var handleAudioEnded = function handleAudioEnded() {
        playButton.style.backgroundImage = "url(".concat(customAudioButton.playImage, ")");
      };

      var handleAudioPlay = function handleAudioPlay() {
        Object.assign(playButton.style, {
          backgroundImage: "url(".concat(customAudioButton.pauseImage, ")"),
          border: '1px solid #ccc'
        });
      };

      var handleAudioPause = function handleAudioPause() {
        Object.assign(playButton.style, {
          backgroundImage: "url(".concat(customAudioButton.playImage, ")"),
          border: '1px solid #326295'
        });
      };

      playButton.addEventListener('click', handlePlayClick);
      audio.addEventListener('play', handleAudioPlay);
      audio.addEventListener('pause', handleAudioPause);
      audio.addEventListener('ended', handleAudioEnded); // store event handler references so they can be removed later

      this._handlePlayClick = handlePlayClick;
      this._handleAudioPlay = handleAudioPlay;
      this._handleAudioPause = handleAudioPause;
      this._handleAudioEnded = handleAudioEnded;
    }
  }, {
    key: "removeCustomAudioButtonListeners",
    value: function removeCustomAudioButtonListeners() {
      var playButton = document.getElementById('play-audio-button');
      var audio = document.querySelector('audio');
      if (!playButton || !audio) return; // remove event listeners using stored references

      playButton.removeEventListener('click', this._handlePlayClick);
      audio.removeEventListener('play', this._handleAudioPlay);
      audio.removeEventListener('pause', this._handleAudioPause);
      audio.removeEventListener('ended', this._handleAudioEnded);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.alignImages();
      this.addCustomAudioButtonControls();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.alignImages();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.removeCustomAudioButtonListeners();
    }
  }, {
    key: "alignImages",
    value: function alignImages() {
      var previewPrompts = document.querySelectorAll('#preview-prompt');
      previewPrompts.forEach(function (previewPrompt) {
        var images = previewPrompt.getElementsByTagName('img');

        if (images && images.length) {
          var _iterator = _createForOfIteratorHelper(images),
              _step;

          try {
            for (_iterator.s(); !(_step = _iterator.n()).done;) {
              var image = _step.value;

              // check if alignment property was set
              if (image.attributes && image.attributes.alignment && image.attributes.alignment.value) {
                var parentNode = image.parentElement; // check if div is not already added to dom and replace current image with wrapped image

                if (!(parentNode.tagName === 'DIV' && parentNode.style.display === 'flex' && parentNode.style.width === '100%')) {
                  var div = document.createElement('div');
                  div.style.display = 'flex';
                  div.style.width = '100%';
                  var copyImage = image.cloneNode(true);
                  div.appendChild(copyImage);
                  parentNode.replaceChild(div, image);
                }
              }
            }
          } catch (err) {
            _iterator.e(err);
          } finally {
            _iterator.f();
          }
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          prompt = _this$props2.prompt,
          classes = _this$props2.classes,
          tagName = _this$props2.tagName,
          className = _this$props2.className,
          onClick = _this$props2.onClick,
          defaultClassName = _this$props2.defaultClassName;
      var CustomTag = tagName || 'div'; // legend tag was added once with accessibility tasks, wee need extra style to make it work with images alignment

      var legendClass = tagName === 'legend' ? 'legend' : '';
      var customClasses = "".concat(classes.promptTable, " ").concat(classes[className] || '', " ").concat(defaultClassName || '', " ").concat(classes[legendClass] || '');
      return /*#__PURE__*/_react["default"].createElement(CustomTag, {
        id: 'preview-prompt',
        onClick: onClick,
        className: customClasses,
        dangerouslySetInnerHTML: {
          __html: this.parsedText(prompt || '').replace(NEWLINE_BLOCK_REGEX, NEWLINE_LATEX)
        }
      });
    }
  }]);
  return PreviewPrompt;
}(_react.Component);

exports.PreviewPrompt = PreviewPrompt;
(0, _defineProperty2["default"])(PreviewPrompt, "propTypes", {
  classes: _propTypes["default"].object,
  prompt: _propTypes["default"].string,
  tagName: _propTypes["default"].string,
  className: _propTypes["default"].string,
  onClick: _propTypes["default"].func,
  defaultClassName: _propTypes["default"].string,
  autoplayAudioEnabled: _propTypes["default"].bool,
  customAudioButton: {
    playImage: _propTypes["default"].string,
    pauseImage: _propTypes["default"].string
  }
});
(0, _defineProperty2["default"])(PreviewPrompt, "defaultProps", {
  onClick: function onClick() {}
});

var styles = function styles(theme) {
  return {
    prompt: {
      verticalAlign: 'middle',
      color: color.text()
    },
    legend: {
      width: '100%',
      fontSize: 'inherit  !important'
    },
    rationale: {
      paddingLeft: theme.spacing.unit * 4,
      paddingBottom: theme.spacing.unit
    },
    label: {
      color: "".concat(color.text(), " !important"),
      //'var(--choice-input-color, black)',
      display: 'flex',
      flexDirection: 'column',
      verticalAlign: 'middle',
      cursor: 'pointer',
      '& > p': {
        margin: '0 0 0 0 !important'
      }
    },
    promptTable: {
      '&:not(.MathJax) > table': {
        borderCollapse: 'collapse'
      },
      '&:not(.MathJax) > table tr': {
        '&:nth-child(2n)': {
          backgroundColor: '#f6f8fa',
          color: theme.palette.common.black
        }
      },
      // align table content to left as per STAR requirement PD-3687
      '&:not(.MathJax) table td, &:not(.MathJax) table th': {
        padding: '.6em 1em',
        textAlign: 'left'
      },
      // added this to fix alignment of text in prompt imported from studio (PD-3423)
      '&:not(.MathJax) > table td > p.kds-indent': {
        textAlign: 'initial'
      }
    }
  };
};

var _default = (0, _styles.withStyles)(styles)(PreviewPrompt);

exports["default"] = _default;
//# sourceMappingURL=preview-prompt.js.map