from Crypto.Hash import SHA256
from .utils import load_keys, create_keys
from simplejson import load
from flask import json
import boto


class S3Store(object):

    def __init__(self, config):
        self.aws_key = config['AWS_KEY']
        self.aws_secret = config['AWS_SECRET']
        self.s3_bucket = config['S3_BUCKET']

    def put_last(self, data):
       #TODO check data integrity using public key
       bucket = self.__get_bucket()
       key_path =  '%s-%s.json ' % (data['title_number'], data['created_ts'])
       key = bucket.new_key(key_path)
       key.set_contents_from_string(json.dumps(data), encrypt_key=True)
       self.__set_new_head(bucket, key_path)

    def get_last(self,):
        bucket = self.__get_bucket()
        return bucket.get_key( 'head.json')

    def get_title(self, title_number, timestamp):
        bucket = self.__get_bucket()
        key = '%s/%d.json' % (title_number, timestamp)
        return bucket.get_key(key)

    def list_titles(self):
        bucket = self.__get_bucket()
        titles = bucket.list()
        latest_titles = []
        for title in titles:
            if 'head.json' in title.name:
                title = bucket.get_key(title.name)
                title_json = load(title)
                title_number = title_json['title_number']
                latest_titles.append({title_number : title_json})
        return latest_titles

    def __set_new_head(self, source_bucket, source_key):
        destination_key  = 'head.json'
        source_bucket.copy_key(destination_key, source_bucket.name,  source_key)

    def __get_bucket(self):
        connection = boto.connect_s3(self.aws_key, self.aws_secret)
        return connection.get_bucket(self.s3_bucket )


class MemoryStore(object):

    def __init__(self):
        self.store = {}

    def get_last(self):
        return self.store.get('head.json')

    def put_last(self, data):
        key =  '%s-%s.json ' % (data['title_number'], data['created_ts'])
        latest_title =  'head.json'
        self.store[key] = data
        self.store[latest_title] = data

    def list_titles(self):
        return [{k.split( '/ ')[0] : v} for k,v in self.store.iteritems() if 'head' in k]

    def clear(self):
        self.store.clear()


@@ -347,24 +347,25 @@
 elf, data):%0A
+%0A
        #TODO
@@ -403,16 +403,169 @@
 lic key%0A
+       # actually probably introduce some chain object to handle validation and%0A       # then just delegate to some storage mechanism for write of file%0A%0A
        b

put a reminder comment in to pick up from next time