from boto.exception import S3ResponseError

from boto.s3.connection import S3Connection
from boto.s3.key import Key

class S3Storage:
    def __init__(self, aws_access_key, aws_secret_key, bucket):
        self.initialized = False

        try:
            self.conn = S3Connection(aws_access_key, aws_secret_key)

            self.bucket = self.conn.lookup(bucket)
            if self.bucket is None:
                self.initialize(bucket)
            else:
                self.initialized = True

        except Exception as e:
            print e


    def put_from_string(self, key, content):
        k = Key(self.bucket)
        k.key = key
        k.set_contents_from_string(content)

    def put(self, filename, key):
        k = Key(self.bucket)
        k.key = key
        k.set_contents_from_filename(filename)

    def get_as_string(self, key):
        k = Key(self.bucket)
        k.key = key

        try:
            return k.get_contents_as_string()
        except S3ResponseError as e:
            return ""

    def get(self, key, filename):
        k = Key(self.bucket)
        k.key = key
        k.get_contents_to_filename(filename)

    def remove(self, key):
        k = Key(self.bucket)
        k.key = key
        k.delete()

    def initialize(self, bucket):
        try:
            self.bucket = self.conn.create_bucket(bucket)
            self.initialized = True
        except Exception as e:
            print e

