"""Client for storing large events into S3."""

from __future__ import absolute_import

import base64
import logging

import boto3


logger = logging.getLogger(__name__)


class LargeEventStore(object):
    """S3 bucket where large Event protobufs are stored.

    Args:
      bucket_name: string name of the S3 Bucket where too-large events are
                   stored
      bucket_key_prefix: string prefixed on keys of too-large events in the
                         S3 bucket
      region: string name of the AWS region where the table is located

    Properties:
      bucket: boto3 s3 Bucket resource
    """

    def __init__(self, bucket_name, bucket_key_prefix, region='us-west-2'):
        self.bucket_name = bucket_name
        self.bucket_name = bucket_name
        if bucket_key_prefix.endswith('/'):
            self.bucket_key_prefix = bucket_key_prefix
        else:
            self.bucket_key_prefix = bucket_key_prefix + '/'
        self.s3 = boto3.resource('s3', region_name=region)
        self._bucket = None

    @property
    def bucket(self):
        if not self._bucket:
            self._bucket = self.s3.Bucket(self.bucket_name)
        return self._bucket

    def PutEvent(self, event):
        """Store event into S3 bucket."""
        key = (self.bucket_key_prefix +
               base64.b64encode(event.uuid) + '.proto')
        logger.info('Putting large event in S3: %s/%s', self.bucket_name, key)
        self.bucket.put_object(
            Key=key,
            Body=event.SerializeToString(),
            ContentType='application/x-protobuf')
