from manifest_edit.plugin.m3u8_main import BasePlugin
from manifest_edit import libfmp4
from schema import Schema, Or, Optional
from manifest_edit.context import Context
import re
from itertools import chain

class Plugin(BasePlugin):
    """A plugin that can rewrite media URIs.

    The main use case is to point players to Manifest Edit URIs to activate
    media playlists use cases.
    """

    _name = __name__

    _keys = ["search", "replace"]

    def schema(self):
        return Schema(
            [
                {
                    self._keys[0]: str,      # selection key
                    self._keys[1]: str,      # selection key
                }
            ]
        )

    def process(self, manifest, storage):

        for config_item in self.config(storage=storage):

            search_value = config_item[self._keys[0]]
            replace_value = config_item[self._keys[1]]
            
            for media in chain(manifest.medias, manifest.streams, manifest.iFrameStreams):
                if media.uri:
                    media.uri=libfmp4.Url(re.sub(search_value, replace_value, str(media.uri)))