import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import React from 'react';
import { getArtifactUrl, globalMediaEventEmitter, isFileIdentifier } from '@atlaskit/media-client';
import { CustomMediaPlayer, MediaPlayer } from '@atlaskit/media-ui';
import { Outcome } from '../domain';
import { MediaViewerError } from '../errors';
import { Video, CustomVideoPlayerWrapper } from '../styleWrappers';
import { isIE } from '../utils/isIE';
import { BaseViewer } from './base-viewer';
import { getObjectUrlFromFileState } from '../utils/getObjectUrlFromFileState';
import { fg } from '@atlaskit/platform-feature-flags';
var sdArtifact = 'video_640.mp4';
var hdArtifact = 'video_1280.mp4';
var localStorageKeyName = 'mv_video_player_quality';
export var VideoViewer = /*#__PURE__*/function (_BaseViewer) {
  function VideoViewer() {
    var _this;
    _classCallCheck(this, VideoViewer);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, VideoViewer, [].concat(args));
    _defineProperty(_this, "onHDChange", function () {
      var isHDActive = !_this.state.isHDActive;
      var preferredQuality = isHDActive ? 'hd' : 'sd';
      localStorage.setItem(localStorageKeyName, preferredQuality);
      _this.setState({
        isHDActive: isHDActive
      });
      _this.init(isHDActive);
    });
    _defineProperty(_this, "onFirstPlay", function () {
      var _this$props = _this.props,
        item = _this$props.item,
        onCanPlay = _this$props.onCanPlay;
      globalMediaEventEmitter.emit('media-viewed', {
        fileId: item.id,
        viewingLevel: 'full'
      });
      onCanPlay && onCanPlay();
    });
    _defineProperty(_this, "onPlay", function () {
      if (fg('platform_media_resume_video_on_token_expiry')) {
        _this.init();
      }
    });
    _defineProperty(_this, "onTimeChanged", function () {
      if (fg('platform_media_resume_video_on_token_expiry')) {
        _this.init();
      }
    });
    _defineProperty(_this, "onError", function () {
      var onError = _this.props.onError;
      onError && onError(new MediaViewerError('videoviewer-playback'));
    });
    return _this;
  }
  _inherits(VideoViewer, _BaseViewer);
  return _createClass(VideoViewer, [{
    key: "initialState",
    get: function get() {
      var item = this.props.item;
      var preferredQuality = fg('platform_media_disable_video_640p_artifact_usage') ? 'hd' : localStorage.getItem(localStorageKeyName);
      return {
        content: Outcome.pending(),
        isHDActive: isHDAvailable(item) && preferredQuality !== 'sd'
      };
    }
  }, {
    key: "renderSuccessful",
    value: function renderSuccessful(content) {
      var isHDActive = this.state.isHDActive;
      var _this$props2 = this.props,
        item = _this$props2.item,
        showControls = _this$props2.showControls,
        previewCount = _this$props2.previewCount,
        identifier = _this$props2.identifier;
      var useCustomVideoPlayer = !isIE();
      var isAutoPlay = previewCount === 0;
      var hdAvailable = isHDAvailable(item);
      var hdActiveOverride = fg('platform_media_disable_video_640p_artifact_usage') ? hdAvailable : isHDActive;
      return useCustomVideoPlayer ? /*#__PURE__*/React.createElement(CustomVideoPlayerWrapper, {
        "data-testid": "media-viewer-video-content"
      }, isFileIdentifier(identifier) && fg('platform_media_video_captions') ? /*#__PURE__*/React.createElement(MediaPlayer, {
        identifier: identifier,
        type: "video",
        isAutoPlay: isAutoPlay,
        onHDToggleClick: this.onHDChange,
        showControls: showControls,
        src: content,
        isHDActive: hdActiveOverride,
        isHDAvailable: hdAvailable,
        isShortcutEnabled: true,
        onFirstPlay: this.onFirstPlay,
        onError: this.onError,
        onPlay: this.onPlay,
        onTimeChanged: this.onTimeChanged,
        lastWatchTimeConfig: {
          contentId: item.id
        }
      }) : /*#__PURE__*/React.createElement(CustomMediaPlayer, {
        type: "video",
        isAutoPlay: isAutoPlay,
        onHDToggleClick: this.onHDChange,
        showControls: showControls,
        src: content,
        fileId: item.id,
        isHDActive: hdActiveOverride,
        isHDAvailable: hdAvailable,
        isShortcutEnabled: true,
        onFirstPlay: this.onFirstPlay,
        onError: this.onError,
        onPlay: this.onPlay,
        onTimeChanged: this.onTimeChanged,
        lastWatchTimeConfig: {
          contentId: item.id
        }
      })) : /*#__PURE__*/React.createElement(Video, {
        autoPlay: isAutoPlay,
        controls: true,
        src: content
      });
    }
  }, {
    key: "init",
    value: function () {
      var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var isHDActive,
          _this$props3,
          mediaClient,
          item,
          collectionName,
          contentUrl,
          hdAvailable,
          hdActiveOverride,
          preferHd,
          _args = arguments;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              isHDActive = _args.length > 0 && _args[0] !== undefined ? _args[0] : this.state.isHDActive;
              _this$props3 = this.props, mediaClient = _this$props3.mediaClient, item = _this$props3.item, collectionName = _this$props3.collectionName;
              _context.prev = 2;
              if (!(item.status === 'processed')) {
                _context.next = 14;
                break;
              }
              hdAvailable = isHDAvailable(item);
              hdActiveOverride = fg('platform_media_disable_video_640p_artifact_usage') ? hdAvailable : isHDActive;
              preferHd = hdActiveOverride && hdAvailable;
              _context.next = 9;
              return mediaClient.file.getArtifactURL(item.artifacts, preferHd ? hdArtifact : sdArtifact, collectionName);
            case 9:
              contentUrl = _context.sent;
              if (contentUrl) {
                _context.next = 12;
                break;
              }
              throw new MediaViewerError("videoviewer-missing-artefact");
            case 12:
              _context.next = 20;
              break;
            case 14:
              _context.next = 16;
              return getObjectUrlFromFileState(item);
            case 16:
              contentUrl = _context.sent;
              if (contentUrl) {
                _context.next = 20;
                break;
              }
              this.setState({
                content: Outcome.pending()
              });
              return _context.abrupt("return");
            case 20:
              this.setState({
                content: Outcome.successful(contentUrl)
              });
              _context.next = 26;
              break;
            case 23:
              _context.prev = 23;
              _context.t0 = _context["catch"](2);
              this.setState({
                content: Outcome.failed(new MediaViewerError('videoviewer-fetch-url', _context.t0 instanceof Error ? _context.t0 : undefined))
              });
            case 26:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[2, 23]]);
      }));
      function init() {
        return _init.apply(this, arguments);
      }
      return init;
    }()
  }, {
    key: "release",
    value: function release() {}
  }]);
}(BaseViewer);
function isHDAvailable(file) {
  if (file.status !== 'processed') {
    return false;
  }
  return !!getArtifactUrl(file.artifacts, hdArtifact);
}