1from __future__ import annotations
2
3import collections
4import contextlib
5import os.path
6from typing import Generator
7
8from babi.user_data import xdg_data
9
10
11class History:
12    def __init__(self) -> None:
13        self._orig_len: dict[str, int] = collections.defaultdict(int)
14        self.data: dict[str, list[str]] = collections.defaultdict(list)
15        self.prev: dict[str, str] = {}
16
17    @contextlib.contextmanager
18    def save(self) -> Generator[None, None, None]:
19        history_dir = xdg_data('history')
20        os.makedirs(history_dir, exist_ok=True)
21        for filename in os.listdir(history_dir):
22            history_filename = os.path.join(history_dir, filename)
23            with open(history_filename, encoding='UTF-8') as f:
24                self.data[filename] = f.read().splitlines()
25                self._orig_len[filename] = len(self.data[filename])
26        try:
27            yield
28        finally:
29            for k, v in self.data.items():
30                new_history = v[self._orig_len[k]:]
31                if new_history:
32                    history_filename = os.path.join(history_dir, k)
33                    with open(history_filename, 'a+', encoding='UTF-8') as f:
34                        f.write('\n'.join(new_history) + '\n')
35