"""
Database of blocking packages:
    entry = 'package==version'
    key = entry, value = list of entries
Every operation is immediately stored in file.
"""
import os
from collections import UserDict


class DB(UserDict):
    def __init__(self):
        """Initialize from file (create an empty file if missing)."""
        super().__init__()
        self.filename = os.path.join(os.environ.get('USERPROFILE'),
                                     '.pip-dater.db')
        try:
            with open(self.filename, 'r') as f:
                raw = [l.split(';') for l in f.read().splitlines()]
        except:
            with open(self.filename, 'w') as fw:
                fw.write('')
            raw = []                
        for l in raw:
            self[l[0]] = l[1].split(',')
        
    def write(self):
        with open(self.filename, 'w') as fw:
            for package, blockers in self.items():
                fw.write(f"{package};{','.join(blockers)}\n")

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.write()

    def remove(self, key):
        if key in self:
            self.pop(key)
            self.write()


##########################
if __name__ == "__main__":
    db = DB()
    db.remove('test_x')
    db['test_a'] = ['a1']
    db['test_b'] = ['b1', 'b2']
    db['test_c'] = ['c1', 'c2', 'c3']
    db.remove('test_b')
    print(db)
    db = DB()
    print(db)
    db.remove('test_a')
    db.remove('test_c')
       