from models.model import Model
from models.profile import Profile

class Preset(Model):
    def __init__(self):
        super().__init__()
        # Backfill profile ownership for existing presets.
        try:
            profiles = Profile()
            profile_list = profiles.list()
            default_profile_id = profile_list[0] if profile_list else None
            changed = False
            for preset_id, preset_data in list(self.items()):
                if isinstance(preset_data, dict) and "profile_id" not in preset_data:
                    if default_profile_id is not None:
                        preset_data["profile_id"] = str(default_profile_id)
                        changed = True
            if changed:
                self.save()
        except Exception:
            pass

    def create(self, profile_id=None):
        next_id = self.get_next_id()
        self[next_id] = {
            "name": "",
            "pattern": "",
            "colors": [],
            "background": "#000000",
            "brightness": 0,
            "delay": 0,
            "n1": 0,
            "n2": 0,
            "n3": 0,
            "n4": 0,
            "n5": 0,
            "n6": 0,
            "n7": 0,
            "n8": 0,
            "manual_beat_n": 1,
            "profile_id": str(profile_id) if profile_id is not None else None,
        }
        self.save()
        return next_id


    def read(self, id):
        id_str = str(id)
        if id_str not in self:
            return None
        return self[id_str]
    
    def update(self, id, data):
        id_str = str(id)
        if id_str not in self:
            return False
        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())    
    