import { RxSubscribe } from "@heydovetail/ui-components";
import React from "react";
import { AttachmentPreview, AttachmentService } from "../../AttachmentService";
import { Attachment } from "../../util/attrs";

// HACK: Should not be necessary in TypeScript 2.9
class RxSubscribeAttachmentPreview extends RxSubscribe<AttachmentPreview> {}

export interface Props {
  attachmentService: AttachmentService;
  attachment: Attachment;
  children: (preview: AttachmentPreview) => React.ReactNode;
}

export interface State {
  observable: ReturnType<AttachmentService["getPreview"]>;
}

export class AttachmentPreviewSubscribe extends React.Component<Props, State> {
  public readonly state = stateFromProps(this.props);

  public render() {
    const { observable } = this.state;
    return <RxSubscribeAttachmentPreview to={observable}>{this.props.children}</RxSubscribeAttachmentPreview>;
  }

  static getDerivedStateFromProps: React.GetDerivedStateFromProps<Props, State> = nextProps => stateFromProps(nextProps);
}

function stateFromProps(props: Props): State {
  return { observable: props.attachmentService.getPreview(props.attachment.id) };
}
