import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React from 'react';
import { isImageRepresentationReady, isErrorFileState, addFileAttrsToUrl } from '@atlaskit/media-client';
import { isImageMimeTypeSupportedByBrowser } from '@atlaskit/media-common';
import { getOrientation } from '@atlaskit/media-ui';
import { Outcome } from '../../domain';
import { MediaViewerError } from '../../errors';
import { InteractiveImg } from './interactive-img';
import { BaseViewer } from '../base-viewer';
function processedFileStateToMediaItem(file) {
  return {
    type: 'file',
    details: {
      id: file.id
    }
  };
}
export class ImageViewer extends BaseViewer {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "onLoad", () => {
      this.props.onLoad();
      this.onMediaDisplayed();
    });
    _defineProperty(this, "onImgError", () => {
      this.props.onError(new MediaViewerError('imageviewer-src-onerror'));
    });
  }
  get initialState() {
    return {
      content: Outcome.pending()
    };
  }
  async init() {
    const {
      item: fileState,
      mediaClient,
      collectionName,
      traceContext
    } = this.props;
    if (isErrorFileState(fileState)) {
      return;
    }
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
    try {
      let orientation = 1;
      let objectUrl;
      let originalBinaryImageUrl;
      let isLocalFileReference = false;
      const {
        preview
      } = fileState;
      if (preview) {
        const {
          value,
          origin
        } = await preview;
        if (value instanceof Blob) {
          orientation = await getOrientation(value);
          objectUrl = URL.createObjectURL(value);
          isLocalFileReference = origin === 'local';
        } else {
          objectUrl = value;
        }
      } else if (isImageRepresentationReady(fileState)) {
        const item = processedFileStateToMediaItem(fileState);
        const response = mediaClient.getImage(item.details.id, {
          collection: collectionName,
          mode: 'fit'
        }, controller, true, traceContext);
        this.cancelImageFetch = () => controller === null || controller === void 0 ? void 0 : controller.abort();
        objectUrl = URL.createObjectURL(await response);
      } else {
        this.setState({
          content: Outcome.pending()
        });
        return;
      }
      if (!isLocalFileReference &&
      // objectUrl at this point is binary file already
      !isErrorFileState(fileState) && fileState.status !== 'uploading' && fileState.mediaType === 'image' && isImageMimeTypeSupportedByBrowser(fileState.mimeType)) {
        originalBinaryImageUrl = await mediaClient.file.getFileBinaryURL(fileState.id, collectionName);
      }
      this.setState({
        content: Outcome.successful({
          objectUrl,
          orientation,
          originalBinaryImageUrl
        })
      });
    } catch (err) {
      // TODO : properly handle aborted requests (MS-2843)
      if (!(controller !== null && controller !== void 0 && controller.signal.aborted)) {
        const imgError = new MediaViewerError('imageviewer-fetch-url', err instanceof Error ? err : undefined);
        this.setState({
          content: Outcome.failed(imgError)
        });
        this.props.onError(imgError);
      }
    }
  }
  release() {
    if (this.cancelImageFetch) {
      this.cancelImageFetch();
    }
    this.state.content.whenSuccessful(({
      objectUrl
    }) => {
      this.revokeObjectUrl(objectUrl);
    });
  }

  // This method is spied on by some test cases, so don't rename or remove it.
  revokeObjectUrl(objectUrl) {
    URL.revokeObjectURL(objectUrl);
  }
  renderSuccessful(content) {
    const {
      item,
      onClose,
      contextId,
      collectionName
    } = this.props;
    if (isErrorFileState(item)) {
      return null;
    }
    const src = contextId ? addFileAttrsToUrl(content.objectUrl, {
      id: item.id,
      contextId,
      collection: collectionName
    }) : content.objectUrl;
    return /*#__PURE__*/React.createElement(InteractiveImg, {
      onLoad: this.onLoad,
      onError: this.onImgError,
      src: src,
      alt: item.name,
      originalBinaryImageSrc: content.originalBinaryImageUrl,
      orientation: content.orientation,
      onClose: onClose
    });
  }
}