package nxm.minio.intr;

import java.lang.reflect.Method;
import java.util.List;

import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import nxm.minio.lib.MinIOResource;
import nxm.sys.inc.ProvisionalUseOnly;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.ReflectUtil;

/**
  Lists files in an S3 Bucket

  @author Jeanette McCall
*/
@ProvisionalUseOnly("prototype")
public class S3ls extends Intrinsic {

  /** Reference minio Results class */
  static final Class<?> IO_MINIO_RESULT_CLASS = ReflectUtil.getClassForName("io.minio.Result");
  /** Results.get method */
  static final Method IO_MINIO_RESULT_GET = ReflectUtil.getMethodOfClass(IO_MINIO_RESULT_CLASS, "get");

  /** default constructor */
  public S3ls () {}

  public int open () {
    String url  = MA.getCS("URL");

    MinIOResource minRes = new MinIOResource(url);
    MinioClient minioClient = minRes.getMinioClient();
    String specifiedBucket = minRes.getBucket();
    boolean allBuckets = "".equals(specifiedBucket);
    try {
      List<Bucket> bucketList = minioClient.listBuckets();
      for (Bucket bucket : bucketList) {
        if (allBuckets || specifiedBucket.equals(bucket.name())) {
          M.println(bucket.creationDate() + ", " + bucket.name());
          Iterable<?> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucket.name()).recursive(true).build());
          for (Object r : results) {
            Item item = (Item)IO_MINIO_RESULT_GET.invoke(r);
            M.println(item.lastModified() + "\t"+item.size()+"\t"+item.objectName());
          }
        }
      }
    }
    catch (Exception e) {
      M.warnStackTrace("FAILED S3LS URL="+url, e);
    }

    return FINISH;
  }

}
