from models.model import Model


class Group(Model):
    """Device groups (members + optional Wi‑Fi driver defaults); also pattern fields for sequences.

    Omit ``profile_id`` (or set it null) for a **shared** group: every profile can attach it to
    zones and sequences. Set ``profile_id`` to a profile id to show the group only when that
    profile is active (still one global record in ``group.json``).
    """

    def __init__(self):
        super().__init__()

    def load(self):
        super().load()
        changed = False
        for gid, doc in list(self.items()):
            if not isinstance(doc, dict):
                continue
            if self._migrate_record(doc):
                changed = True
        if changed:
            self.save()

    def _migrate_record(self, doc):
        changed = False
        raw_dev = doc.get("devices")
        if raw_dev is None:
            doc["devices"] = []
            changed = True
        elif isinstance(raw_dev, list):
            norm = []
            for x in raw_dev:
                if x is None:
                    continue
                s = str(x).strip().lower().replace(":", "").replace("-", "")
                if len(s) == 12 and all(c in "0123456789abcdef" for c in s):
                    norm.append(s)
                else:
                    norm.append(str(x).strip())
            if norm != raw_dev:
                doc["devices"] = norm
                changed = True
        for key in (
            "wifi_driver_display_name",
            "wifi_driver_num_leds",
            "wifi_color_order",
            "wifi_startup_mode",
        ):
            if key not in doc:
                doc[key] = None
                changed = True
        if "output_brightness" not in doc:
            doc["output_brightness"] = 255
            changed = True
        return changed

    def create(self, name=""):
        next_id = self.get_next_id()
        self[next_id] = {
            "name": name,
            "devices": [],
            "wifi_driver_display_name": None,
            "wifi_driver_num_leds": None,
            "wifi_color_order": None,
            "wifi_startup_mode": None,
            "output_brightness": 255,
            "pattern": "on",
            "colors": ["000000", "FF0000"],
            "brightness": 100,
            "delay": 100,
            "step_offset": 0,
            "step_increment": 1,
            "n1": 0,
            "n2": 0,
            "n3": 0,
            "n4": 0,
            "n5": 0,
            "n6": 0,
            "n7": 0,
            "n8": 0,
        }
        self.save()
        return next_id

    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
        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())
