import _defineProperty from "@babel/runtime/helpers/defineProperty";
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';
const sdArtifact = 'video_640.mp4';
const hdArtifact = 'video_1280.mp4';
const localStorageKeyName = 'mv_video_player_quality';
export class VideoViewer extends BaseViewer {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "onHDChange", () => {
      const isHDActive = !this.state.isHDActive;
      const preferredQuality = isHDActive ? 'hd' : 'sd';
      localStorage.setItem(localStorageKeyName, preferredQuality);
      this.setState({
        isHDActive
      });
      this.init(isHDActive);
    });
    _defineProperty(this, "onFirstPlay", () => {
      const {
        item,
        onCanPlay
      } = this.props;
      globalMediaEventEmitter.emit('media-viewed', {
        fileId: item.id,
        viewingLevel: 'full'
      });
      onCanPlay && onCanPlay();
    });
    _defineProperty(this, "onPlay", () => {
      if (fg('platform_media_resume_video_on_token_expiry')) {
        this.init();
      }
    });
    _defineProperty(this, "onTimeChanged", () => {
      if (fg('platform_media_resume_video_on_token_expiry')) {
        this.init();
      }
    });
    _defineProperty(this, "onError", () => {
      const {
        onError
      } = this.props;
      onError && onError(new MediaViewerError('videoviewer-playback'));
    });
  }
  get initialState() {
    const {
      item
    } = this.props;
    const preferredQuality = fg('platform_media_disable_video_640p_artifact_usage') ? 'hd' : localStorage.getItem(localStorageKeyName);
    return {
      content: Outcome.pending(),
      isHDActive: isHDAvailable(item) && preferredQuality !== 'sd'
    };
  }
  renderSuccessful(content) {
    const {
      isHDActive
    } = this.state;
    const {
      item,
      showControls,
      previewCount,
      identifier
    } = this.props;
    const useCustomVideoPlayer = !isIE();
    const isAutoPlay = previewCount === 0;
    const hdAvailable = isHDAvailable(item);
    const 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
    });
  }
  async init(isHDActive = this.state.isHDActive) {
    const {
      mediaClient,
      item,
      collectionName
    } = this.props;
    try {
      let contentUrl;
      if (item.status === 'processed') {
        const hdAvailable = isHDAvailable(item);
        const hdActiveOverride = fg('platform_media_disable_video_640p_artifact_usage') ? hdAvailable : isHDActive;
        const preferHd = hdActiveOverride && hdAvailable;
        contentUrl = await mediaClient.file.getArtifactURL(item.artifacts, preferHd ? hdArtifact : sdArtifact, collectionName);
        if (!contentUrl) {
          throw new MediaViewerError(`videoviewer-missing-artefact`);
        }
      } else {
        contentUrl = await getObjectUrlFromFileState(item);
        if (!contentUrl) {
          this.setState({
            content: Outcome.pending()
          });
          return;
        }
      }
      this.setState({
        content: Outcome.successful(contentUrl)
      });
    } catch (error) {
      this.setState({
        content: Outcome.failed(new MediaViewerError('videoviewer-fetch-url', error instanceof Error ? error : undefined))
      });
    }
  }
  release() {}
}
function isHDAvailable(file) {
  if (file.status !== 'processed') {
    return false;
  }
  return !!getArtifactUrl(file.artifacts, hdArtifact);
}