'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var neetoCist = require('@bigbinary/neeto-cist');
var Pane = require('@bigbinary/neetoui/Pane');
var Typography = require('@bigbinary/neetoui/Typography');
var Spinner = require('@bigbinary/neetoui/Spinner');
var reactI18next = require('react-i18next');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var Label = require('@bigbinary/neetoui/Label');
var Input = require('@bigbinary/neetoui/Input');
var Switch = require('@bigbinary/neetoui/Switch');
var Button = require('@bigbinary/neetoui/Button');
var ramda = require('ramda');
var CopyToClipboardButton = require('./CopyToClipboardButton.js');
var jsxRuntime = require('react/jsx-runtime');
require('classnames');
require('@bigbinary/neeto-commons-frontend/utils/general');
require('@bigbinary/neeto-icons/Copy');
require('@bigbinary/neeto-icons/Check');
require('./inject-css-B6qYtOJe.js');

var ONE_SECOND = 1;
var ONE_MINUTE = 60 * ONE_SECOND;
var ONE_HOUR = 60 * ONE_MINUTE;

var padZero = function padZero(number) {
  var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  var string = String(number);
  var threshold = Math.pow(10, length - 1);
  if (number < threshold) {
    while (String(threshold).length > string.length) {
      string = "0".concat(number);
    }
  }
  return string;
};
var shouldRenderHoursInput = function shouldRenderHoursInput(duration) {
  var hours = Math.floor(duration / ONE_HOUR);
  return hours > 0;
};
var formatTime = function formatTime(timeInSeconds, showHours) {
  var hours = Math.floor(timeInSeconds / ONE_HOUR);
  var minutes = Math.floor(timeInSeconds % ONE_HOUR / ONE_MINUTE);
  var seconds = timeInSeconds % ONE_MINUTE;
  return showHours ? "".concat(padZero(hours), ":").concat(padZero(minutes), ":").concat(padZero(seconds)) : "".concat(padZero(minutes), ":").concat(padZero(seconds));
};
var parseTime = function parseTime(timeString) {
  var parts = timeString.split(":").map(function (part) {
    return part === "" ? NaN : parseInt(part, 10);
  });
  if (parts.some(isNaN) || parts.length > 3) {
    return 0;
  }
  if (parts.length === 1) {
    return parts[0];
  } else if (parts.length === 2) {
    return parts[0] * ONE_MINUTE + parts[1];
  } else if (parts.length === 3) {
    return parts[0] * ONE_HOUR + parts[1] * ONE_MINUTE + parts[2];
  }
  return 0;
};
var validateInput = function validateInput(input) {
  var regex = /^[0-9:]{0,8}$/;
  var colons = (input.match(/:/g) || []).length;
  return regex.test(input) && colons <= 2;
};

var SharePaneBody = function SharePaneBody(_ref) {
  var recordingUrls = _ref.recordingUrls,
    totalDuration = _ref.totalDuration,
    getCurrentTimestamp = _ref.getCurrentTimestamp,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    Preview = _ref.preview,
    enableAutoplayAndMuteFlags = _ref.enableAutoplayAndMuteFlags;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var currentTimestamp = getCurrentTimestamp();
  var _useState = React.useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    shareLinks = _useState2[0],
    setShareLinks = _useState2[1];
  var _useState3 = React.useState(currentTimestamp),
    _useState4 = _slicedToArray(_useState3, 2),
    currentPlaybackTime = _useState4[0],
    setCurrentPlaybackTime = _useState4[1];
  var _useState5 = React.useState({
      muted: false,
      autoplay: false
    }),
    _useState6 = _slicedToArray(_useState5, 2),
    params = _useState6[0],
    setParams = _useState6[1];
  var muted = params.muted,
    autoplay = params.autoplay;
  var _useState7 = React.useState(""),
    _useState8 = _slicedToArray(_useState7, 2),
    rawInput = _useState8[0],
    setRawInput = _useState8[1];
  var showHours = shouldRenderHoursInput(totalDuration);
  var handlePlaybackTimestampChange = function handlePlaybackTimestampChange(e) {
    var input = e.target.value;
    if (validateInput(input)) {
      setRawInput(input);
    }
  };
  var handleFlagsChange = function handleFlagsChange(key, value) {
    return setParams(ramda.assoc(key, value));
  };
  var formatAndSetTime = function formatAndSetTime() {
    var timeInSeconds = parseTime(rawInput);
    if (timeInSeconds > totalDuration) {
      timeInSeconds = totalDuration;
    }
    setRawInput(formatTime(timeInSeconds, showHours));
  };
  var handleKeyDown = function handleKeyDown(e) {
    if (e.key !== "Enter") return;
    formatAndSetTime();
  };
  var generateUrls = React.useCallback(function (timeInSeconds, urlParams) {
    var playbackUrls = recordingUrls.map(function (recordingUrl) {
      return utils.buildUrl(recordingUrl, {
        time: timeInSeconds,
        muted: urlParams.muted ? 1 : undefined,
        autoplay: urlParams.autoplay ? 1 : undefined
      });
    });
    setShareLinks(playbackUrls);
  }, [recordingUrls]);
  var handleRegenerateUrl = function handleRegenerateUrl() {
    var timeInSeconds = parseTime(rawInput);
    if (timeInSeconds > totalDuration) {
      timeInSeconds = totalDuration;
    }
    setCurrentPlaybackTime(timeInSeconds);
    generateUrls(timeInSeconds, params);
  };
  React.useEffect(function () {
    if (ramda.not(isOpen)) return;
    var initialTime = currentTimestamp > 0 ? currentTimestamp : 0;
    var initialParams = {
      muted: false,
      autoplay: false
    };
    setCurrentPlaybackTime(initialTime);
    setRawInput(formatTime(initialTime, showHours));
    setParams(initialParams);
    generateUrls(initialTime, initialParams);
  }, [isOpen, showHours, currentTimestamp, generateUrls]);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex w-full flex-col gap-8",
    children: [/*#__PURE__*/jsxRuntime.jsx("div", {
      className: "neeto-ui-border-gray-200 flex flex-col gap-8 border-b px-6 pb-8",
      children: /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex w-full flex-col gap-6",
        children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex flex-col gap-y-2",
          children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
            style: "h4",
            children: t("neetoMolecules.shareRecording.configureUrlParameters")
          }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
            style: "body3",
            children: t("neetoMolecules.shareRecording.configureUrlParametersDescription")
          })]
        }), /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex items-center gap-x-3",
          children: [/*#__PURE__*/jsxRuntime.jsx(Label, {
            children: t("neetoMolecules.shareRecording.startVideoAt")
          }), /*#__PURE__*/jsxRuntime.jsx(Input, {
            unlimitedChars: true,
            className: "w-full max-w-32",
            "data-testid": "time-input",
            placeholder: showHours ? "HH:MM:SS" : "MM:SS",
            value: rawInput,
            onBlur: formatAndSetTime,
            onChange: handlePlaybackTimestampChange,
            onKeyDown: handleKeyDown
          })]
        }), enableAutoplayAndMuteFlags && /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex flex-col gap-4",
          children: [/*#__PURE__*/jsxRuntime.jsx(Switch, {
            checked: muted,
            "data-testid": "muted-checkbox",
            id: "muted",
            label: t("neetoMolecules.shareRecording.muted"),
            name: "muted",
            onChange: function onChange(e) {
              return handleFlagsChange("muted", e.target.checked);
            }
          }), /*#__PURE__*/jsxRuntime.jsx(Switch, {
            checked: autoplay,
            "data-testid": "autoplay-checkbox",
            id: "autoplay",
            label: t("neetoMolecules.shareRecording.autoplay"),
            name: "autoplay",
            onChange: function onChange(e) {
              return handleFlagsChange("autoplay", e.target.checked);
            }
          })]
        }), /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "mt-2 flex items-center gap-x-3",
          children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
            "data-testid": "regenerate-url-button",
            label: t("neetoMolecules.shareRecording.regenerateUrl"),
            size: "small",
            onClick: handleRegenerateUrl
          }), /*#__PURE__*/jsxRuntime.jsx(Button, {
            "data-testid": "cancel-button",
            label: t("neetoMolecules.shareRecording.cancel"),
            size: "small",
            style: "text",
            onClick: onClose
          })]
        })]
      })
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex flex-col gap-6 px-6",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex flex-col gap-y-2",
        children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
          style: "h4",
          children: t("neetoMolecules.shareRecording.generatedUrls")
        }), /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "flex flex-col gap-y-3",
          children: shareLinks.map(function (shareLink, index) {
            return /*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "neeto-ui-bg-gray-100 neeto-ui-rounded flex w-full items-start justify-between gap-2 p-2",
              children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "min-w-0 flex-1 break-words",
                style: "body2",
                children: shareLink
              }), /*#__PURE__*/jsxRuntime.jsx(CopyToClipboardButton, {
                className: "flex-shrink-0",
                size: "small",
                style: "text",
                value: shareLink
              })]
            }, index);
          })
        })]
      }), Preview && /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex flex-col gap-y-2",
        children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
          style: "h4",
          children: t("neetoMolecules.shareRecording.preview")
        }), /*#__PURE__*/jsxRuntime.jsx(Preview, {
          currentPlaybackTime: currentPlaybackTime
        })]
      })]
    })]
  });
};

var _excluded = ["recordingUrl", "recordingUrls", "totalDuration", "getCurrentTimestamp", "isOpen", "onClose", "isLoading", "preview", "enableAutoplayAndMuteFlags", "size"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var ShareRecordingPane = function ShareRecordingPane(_ref) {
  var _ref$recordingUrl = _ref.recordingUrl,
    recordingUrl = _ref$recordingUrl === void 0 ? null : _ref$recordingUrl,
    _ref$recordingUrls = _ref.recordingUrls,
    recordingUrls = _ref$recordingUrls === void 0 ? [] : _ref$recordingUrls,
    totalDuration = _ref.totalDuration,
    getCurrentTimestamp = _ref.getCurrentTimestamp,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    _ref$isLoading = _ref.isLoading,
    isLoading = _ref$isLoading === void 0 ? false : _ref$isLoading,
    preview = _ref.preview,
    _ref$enableAutoplayAn = _ref.enableAutoplayAndMuteFlags,
    enableAutoplayAndMuteFlags = _ref$enableAutoplayAn === void 0 ? false : _ref$enableAutoplayAn,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? "large" : _ref$size,
    otherProps = _objectWithoutProperties(_ref, _excluded);
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var recordingUrlsToShare = neetoCist.isNotEmpty(recordingUrls) ? recordingUrls : [recordingUrl];
  return /*#__PURE__*/jsxRuntime.jsxs(Pane, _objectSpread(_objectSpread({}, _objectSpread({
    isOpen: isOpen,
    onClose: onClose,
    size: size
  }, otherProps)), {}, {
    "data-testid": "share-pane",
    children: [/*#__PURE__*/jsxRuntime.jsx(Pane.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
        style: "h2",
        children: t("neetoMolecules.shareRecording.title")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(Pane.Body, {
      className: "neeto-ui-border-gray-200 border-t px-0 py-6",
      children: isLoading ? /*#__PURE__*/jsxRuntime.jsx(Spinner, {
        className: "mx-auto"
      }) : /*#__PURE__*/jsxRuntime.jsx(SharePaneBody, {
        enableAutoplayAndMuteFlags: enableAutoplayAndMuteFlags,
        getCurrentTimestamp: getCurrentTimestamp,
        isOpen: isOpen,
        onClose: onClose,
        preview: preview,
        totalDuration: totalDuration,
        recordingUrls: recordingUrlsToShare
      })
    })]
  }));
};

module.exports = ShareRecordingPane;
//# sourceMappingURL=ShareRecordingPane.js.map
