# AUTOGENERATED! DO NOT EDIT! File to edit: s3bz.ipynb (unless otherwise specified).

__all__ = ['S3']

# Cell
from botocore.config import Config
import bz2, json, boto3

# Cell
class S3:
  @staticmethod
  def s3(region = 'ap-southeast-1', user = None, pw = None):
    '''
    create and return s3 client
    '''
    config = Config(s3={"use_accelerate_endpoint": True,
                        "addressing_style": "virtual"})
    s3 = boto3.client(
        's3',
        aws_access_key_id= user,
        aws_secret_access_key= pw,
        region_name = region,
        config = config
      )
    return s3
  @classmethod
  def save(cls,  key, objectToSave, bucket = '', user=None, pw=None):
    '''
    save an object to s3
    '''
    s3 = cls.s3(user=user, pw=pw)
    compressedData = bz2.compress(json.dumps(objectToSave).encode())
    result = s3.put_object(Body=compressedData, Bucket=bucket, Key=key)
    success = result['ResponseMetadata']['HTTPStatusCode'] ==  200
    print('data was saved to s3')
    if not success: raise Error(success)
    else: return True
  @classmethod
  def exist(cls, key, bucket, user=None, pw=None):
    return 'Contents' in cls.s3(user=user,pw=pw).list_objects(
        Bucket=bucket , Prefix=key )
  @classmethod
  def load(cls, key, bucket='', user= None, pw= None):
    if not cls.exist(key, bucket):
      return {}
    s3 = cls.s3(user=user, pw=pw)
    requestResult =  s3.get_object(
                  Bucket = bucket,
                  Key = key
                )
    allItemsByte = next(requestResult.get('Body',None))
    if not allItemsByte: raise ValueError('all data does not exist in the database')
    allItems = json.loads(bz2.decompress(allItemsByte).decode())
    return allItems

  @classmethod
  def presign(cls, key, expiry = 1000, bucket = ''):
    if not cls.checkIfExist(key,bucket=bucket): return 'object doesnt exist'
    s3 = cls.s3()
    result = s3.generate_presigned_url(
        'get_object',
          Params={'Bucket': bucket,
                  'Key': key},
        ExpiresIn=expiry)
    return result

  @classmethod
  def checkIfExist(cls, key, bucket = ''):
    results = cls.s3().list_objects(Bucket=bucket , Prefix= key)
    return 'Contents' in results