package nxm.minio.intr;

import io.minio.CopyObjectArgs;
import io.minio.CopySource;
import io.minio.DownloadObjectArgs;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.UploadObjectArgs;
import nxm.minio.lib.MinIOResource;
import nxm.sys.inc.ProvisionalUseOnly;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.Shell;

/**
  Renames file in an S3 Bucket

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

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

  public int open () {
    String url  = MA.getCS("URL");
    MinIOResource minRes = new MinIOResource(url);
    MinioClient minioClient = minRes.getMinioClient();
    String newLoc = MA.getCS("NAME");
    int bucketKeySep = newLoc.indexOf('/');
    String newKey = (bucketKeySep < 0) ? newLoc : newLoc.substring(bucketKeySep+1);
    String newBucket = (bucketKeySep < 0) ? minRes.getBucket() : newLoc.substring(0,bucketKeySep);
    try {
      // copy
      minioClient.copyObject(CopyObjectArgs.builder().bucket(newBucket).object(newKey)
          .source(CopySource.builder().bucket(minRes.getBucket()).object(minRes.getKey()).build())
          .build());
      // remove original
      minioClient.removeObject(RemoveObjectArgs.builder().bucket(minRes.getBucket()).object(minRes.getKey()).build());
    }
    catch (Exception e) {
      M.warnStackTrace("FAILED S3RENAME URL="+url+" NAME="+newKey, e);
    }

    return FINISH;
  }

}
