package nxm.minio.intr;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import nxm.minio.lib.MinIOResource;
import nxm.sys.inc.ProvisionalUseOnly;
import nxm.sys.lib.FileName;
import nxm.sys.lib.Intrinsic;

/**
  Puts a file in an S3 Bucket

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

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

  public int open () {
    // Open the file
    FileName fn = new FileName(MA.getCS("FILE"));
    String url  = MA.getCS("URL");
    MinIOResource minRes = new MinIOResource(url);
    MinioClient minioClient = minRes.getMinioClient();
    String bucket = minRes.getBucket();
    try {
      boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
      if (!bucketExists) minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
      minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucket).object(minRes.getKey()).filename(fn.toLocalFileName()).build());
    }
    catch (Exception e) {
      M.warnStackTrace("FAILED S3PUT FILE="+fn+" URL="+url, e);
    }

    return FINISH;
  }

}
