from schema import Schema, Or, Optional
import re

class ExtXMediaSelection:
    """
    A class supporting common methods to select EXT-X-MEDIA elements
    in a master playlist based on a plugins' yaml config
    """

    keys = ["type", "group-id", "language", "uri", "name"]

    def dictSchema(self):
        return {
            self.keys[0]: Or("AUDIO", "SUBTITLES", "VIDEO", "CLOSED-CAPTIONS"),      # selection key
            Optional(self.keys[1], default=r".*"): str,  # selection key
            Optional(self.keys[2], default=r".*"): str,  # selection key
            Optional(self.keys[3], default=r".*"): str,  # selection key
            Optional(self.keys[4], default=r".*"): str,  # selection key
        }

    
    def medias(self, config_item, manifest):

        type_value = config_item[self.keys[0]]
        group_id = config_item[self.keys[1]]
        language = config_item[self.keys[2]]
        uri = config_item[self.keys[3]]
        name = config_item[self.keys[4]]

        for media in manifest.medias:
            if re.fullmatch(type_value, media.type):
                if re.fullmatch(group_id, media.groupId):
                    if re.fullmatch(language, media.language):
                        if re.fullmatch(name, media.name):
                            # media URI can be None, will be treated as an empty
                            # string
                            media_uri = media.uri.__repr__() if media.uri else ""
                            if re.fullmatch(uri, media_uri):
                                yield media
