import pathlib
import time

STALE_SECONDS = 60 * 60 * 24 * 1 # one day

class DiskCache:
    def __init__(self, root_path):
        self.root_path = pathlib.Path(root_path)
        self.root_path.mkdir(exist_ok=True)
        assert(self.root_path.is_dir())

    def __contains__(self, key):
        self.clear_stale_files()
        return self.root_path.joinpath(key).exists()

    def __getitem__(self, key):
        try:
            with self.root_path.joinpath(key).open('rb') as infile:
                return infile.read()
        except FileNotFoundError:
            raise KeyError(key)

    def __setitem__(self, key, value):
        try:
            with self.root_path.joinpath(key).open('wb') as outfile:
                outfile.write(value)
        except FileNotFoundError:
            raise KeyError(key)

    def __delitem__(self, key):
        try:
            self.root_path.joinpath(key).unlink()
        except FileNotFoundError:
            raise KeyError(key)

    def clear_stale_files(self):
        files_to_delete = []
        for path in self.root_path.iterdir():
            if not path.is_file():
                continue
            age = time.time() - path.stat().st_mtime
            if age >= STALE_SECONDS:
                files_to_delete.append(path)
        for path in files_to_delete:
            path.unlink()
