import json

one_day_in_seconds = 60 * 60 * 24


class Store(object):
    def __init__(self, raw_store, unique_id):
        self.raw_store = raw_store
        self.id = unique_id

    def exists(self, key):
        return self.raw_store.exists(self.key(key))

    def set(self, key, value):
        self.raw_store.set(self.key(key), value)
        self.raw_store.expire(self.key(key), one_day_in_seconds)

    def delete(self, key):
        self.raw_store.delete(self.key(key))

    def get(self, key):
        self.raw_store.expire(self.key(key), one_day_in_seconds)
        return self.raw_store.get(self.key(key))

    def append_map_to_list(self, list_id, data):
        self.raw_store.rpush(self.key(list_id), json.dumps(data))

    def replace_map_in_list(self, list_id, data, index):
        self.raw_store.lset(self.key(list_id), index, json.dumps(data))

    def get_list_of_maps(self, list_id):
        key = self.key(list_id)
        result_list = self.raw_store.lrange(key, 0, self.raw_store.llen(key))
        return list(map(lambda x: json.loads(x.decode('utf-8')), result_list))

    def remove_map_from_list(self, list_id, index):
        data_to_remove = self.raw_store.lindex(self.key(list_id), index)
        self.raw_store.lrem(self.key(list_id), data_to_remove)

    def key(self, tag):
        return self.id + ':' + tag
