import readline

import mucus.data


class History:
    def __init__(self, key='items'):
        self.key = key

    def __enter__(self):
        self.restore = [readline.get_history_item(i + 1) for i in range(readline.get_current_history_length())]
        readline.clear_history()
        data = mucus.data.hget('history', self.key)
        if data:
            for s in data:
                readline.add_history(s)
        return self

    def __exit__(self, *args):
        data = [readline.get_history_item(i + 1) for i in range(readline.get_current_history_length())]
        if data:
            mucus.data.hset('history', self.key, data)
        readline.clear_history()
        for s in self.restore:
            readline.add_history(s)
