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

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

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

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

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

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

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

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