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

type Props = {
  client: S3Client;
  bucket: string;
  prefix: string;
};

type State = {
  loaded: boolean;
  folders: string[];
  files: string[];
};

class ObjectList extends React.Component<Props, State> {
  state = {
    loaded: false,
    folders: [],
    files: [],
  };

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

  async componentDidMount() {
    console.log(this.props);

    let command = new ListObjectsV2Command({
      Bucket: this.props.bucket,
      Prefix: this.props.prefix,
      Delimiter: '/',
    });
    try {
      const pxlen = this.props.prefix.length;

      const data = await this.props.client.send(command);
      console.log("ok", data);
      this.setState({
        loaded: true,
        folders: (data.CommonPrefixes || []).map((cp) => cp.Prefix!.substring(pxlen)),
        files: (data.Contents || []).map((obj) => obj.Key!.substring(pxlen)),
      });
    } catch(error) {
      console.log("err", error);
    }
  }

  parentTag() {
    let spl = this.props.prefix.split("/");
    while (spl.pop() == "");
    spl.push("");
    let pp = spl.join("/");
    return (
      <li key="PARENT">
        <Link to={ "/" + this.props.bucket + "/" + pp }>..</Link>
      </li>
    );
  }

  render() {
    let par = (this.props.prefix.length > 0 ?
      this.parentTag()
      : <></>);

    if (!this.state.loaded) {
      return (
        <ul>
          { par }
          <li>Loading...</li>
        </ul>
        );
    }

    return (
      <ul>
        { par }
        { this.state.folders.map((f) =>
          <li key={f + "/" }>
            <Link to={ "/" + this.props.bucket + "/" + this.props.prefix + f }>{ f }</Link>
          </li>
        )}
        { this.state.files.map((f) =>
          <li key={f}>{ f }</li>
        )}
      </ul>
    );
  }
}


interface IClient {
  client: S3Client;
}

export const ObjectList1 = ({ client }: IClient) => {
  const params = useParams();
  const bucket = params["bucket"]!;
  return <>
    <ObjectList client={client} bucket={bucket} prefix="" key={bucket} />
   </>;
};

export const ObjectList2 = ({ client }: IClient) => {
  const params = useParams();
  const bucket = params["bucket"]!;
  const prefix = params["*"] || "";
  const key = bucket + "/" + prefix;
  return <>
    <ObjectList client={client} bucket={bucket} prefix={prefix} key={key} />
  </>;
};
