from manifest_edit.plugin.m3u8_main import BasePlugin
from schema import Schema, Or
from manifest_edit.context import Context
from manifest_edit.plugins.utility.m3u8_main.ext_x_media_selection import ExtXMediaSelection
from schema import Schema, Or, Optional
from copy import copy
import re


class Plugin(BasePlugin):
    """A plugin that can remove selected EXT-X-MEDIA tags from a main playlist
    at the same time removing any affected EXT-X-STREAMS-INF if necessary.

    E.g. when removing an EXT-X-MEDIA tag with a certain audio group, if
    that was the last one referencing that group, then remove also all the
    EXT-X-STREAM-INF entries referencing that group.

    """

    _name = __name__

    _keys = ["remove"]

    def schema(self):
        return Schema([
            ExtXMediaSelection().dictSchema()
        ])
        
    def remove_streams(self, manifest, type, groupId):
        streams_to_remove = []
        for stream in manifest.streams:
            for group in stream.groups:
                if group[0] == type and group[1] == groupId:
                    streams_to_remove.append(copy(stream))

        for stream in streams_to_remove:
            manifest.streams.remove(stream)

    def process(self, manifest, storage):
        if not len(manifest.medias):
            Context.log_warning(
                "The provided m3u8 manifest does not have"
                " an EXT-X-MEDIA section! Skipping..."
            )
            return
        
        medias_to_remove = []
        for config_item in self.config(storage=storage):
            for media in ExtXMediaSelection().medias(config_item, manifest):
                medias_to_remove.append(copy(media))

        # We have a list of media to remove. Let's remove them
        for media in medias_to_remove:
            manifest.medias.remove(media)

            #Check if now there are no more medias with the same
            #TYPE and GROUP-ID
            medias_left = [m for m in manifest.medias if m.type==media.type and m.groupId==media.groupId]
            if not medias_left:
                # Remove all streams that referenced the non-existing group
                self.remove_streams(manifest, media.type, media.groupId)

