import uuid
from collections.abc import Mapping
import datetime
import yaml
class TokenCollection(Mapping):
    def __init__(self, filename: str):
        self.filename=filename
        with open(filename,"r") as f:
            self.d=yaml.load(f.read(),yaml.Loader)
            if self.d is None:
                self.d=dict()

    def save(self):
        with open(self.filename,"w") as f:
            f.write(yaml.dump(self.d))
    def __getitem__(self,key):
        return d[key]

    def is_valid(self, token, days=1):
        if not token in self.d:
            return False
        #return self.d[token]["created"] + datetime.timedelta(days=days)
        #print(self.d[token]["created"] + datetime.timedelta(days=days))
        if self.d[token]["created"] + datetime.timedelta(days=days) > datetime.datetime.now():
            return True
        return False

    def create(self, created_by="Anonym"):
        t=uuid.uuid4()
        self.d[str(t)]={
            "created": datetime.datetime.now(),
            "createdby":  created_by
        }
        self.save()
        return str(t)

    def __iter__(self):
        return iter(self.d)

    def __len__(self):
        return len(self.d)