from models.model import Model

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

    def create(self, name="", colors=None):
        next_id = self.get_next_id()
        # Store palette as a simple list of colors; name is ignored.
        self[next_id] = list(colors) if colors else []
        self.save()
        return next_id

    def read(self, id):
        id_str = str(id)
        value = self.get(id_str, None)
        # Backwards compatibility: if stored as {"colors": [...]}, unwrap.
        if isinstance(value, dict) and "colors" in value:
            return value.get("colors") or []
        # Otherwise, expect a list of colors.
        return value or []
    
    def update(self, id, data):
        id_str = str(id)
        if id_str not in self:
            return False
        # Accept either {"colors": [...]} or a raw list.
        if isinstance(data, dict):
            colors = data.get("colors", [])
        else:
            colors = data
        self[id_str] = list(colors) if colors else []
        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())
