from models.model import Model


class Pattern(Model):
    def __init__(self):
        super().__init__()

    def create(self, name="", data=None):
        pattern_name = str(name).strip()
        if not pattern_name:
            pattern_name = self.get_next_id()
        self[pattern_name] = data if isinstance(data, dict) else {}
        self.save()
        return pattern_name

    def read(self, id):
        id_str = str(id)
        return self.get(id_str, None)

    def update(self, id, data):
        id_str = str(id)
        if id_str not in self:
            return False
        if isinstance(data, dict):
            self[id_str].update(data)
        self.save()
        return True

    def delete(self, id):
        id_str = str(id)
        if id_str not in self:
            return False
        self.pop(id_str)
        self.save()
        return True

    def list(self):
        return list(self.keys())
