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

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

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

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

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

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

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

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