import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { S3Client, ListObjectsV2Command, HeadObjectCommand } from '@aws-sdk/client-s3';

import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import { BsFileEarmarkText, BsDownload } from 'react-icons/bs';

import downloadFile from './downloadFile';
import fileSizePretty from './fileSizePretty';

type Props = {
  client: S3Client;
  bucket: string;
  s3key: string;
  filename: string;
};

type State = {
  show: boolean;
  loaded: boolean;
  size: number;
  contentType: string;
};

class ObjectInfo extends React.Component<Props, State> {
  state = {
    show: true,
    loaded: false,
    size: 0,
    contentType: "",
  };

  constructor(props: Props) {
    super(props);
  }

  async componentDidMount() {
    let command = new HeadObjectCommand({
      Bucket: this.props.bucket,
      Key: this.props.s3key,
    });

    const data = await this.props.client.send(command);

    this.setState({
      loaded: true,
      size: data.ContentLength!,
      contentType: data.ContentType || "",
    });
  }
  
  handleClose() {
    this.setState({show: false});
  }

  render() {
    return <>
      <Modal show={this.state.show} onHide={() => this.handleClose()}>
        <Modal.Header closeButton>
          <Modal.Title><BsFileEarmarkText /> { this.props.filename }</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <p><strong>Bucket:</strong> { this.props.bucket }</p>
          <p><strong>Key:</strong> { this.props.s3key }</p>
          { this.state.loaded ?
            <>
              <p><strong>Size:</strong> { fileSizePretty(this.state.size) }</p>
              <p><strong>Content type:</strong> { this.state.contentType }</p>
            </>
          : <></> }
        </Modal.Body>
        <Modal.Footer>
          <Button variant="primary" onClick={() =>
            downloadFile(this.props.client, this.props.bucket, this.props.s3key, this.props.filename)
          }>
             <BsDownload /> Download
          </Button>
        </Modal.Footer>
      </Modal>
    </>;
  }
};

export default ObjectInfo;
