from manifest_edit import libfmp4
from manifest_edit.plugin.mpd.base_plugin import BasePlugin
from manifest_edit.context import Context
from schema import Schema


class Plugin(BasePlugin):
    """
    EventStream value add plugin.

    This plugins covers a very specific use case, where a certain device
    would require the presence of a "value" field in an EventStream or
    it would crash. (!)

    Despite recognizing that "value" is optional and that this behaviour is
    clearly faulty on the device side, this plugin seems the
    easiest way forward to provide compatibility.

    Specifically, this plugin changes

    <EventStream
     schemeIdUri="urn:scte:scte35:2014:xml+bin" 
     timescale="1">

    to

    <EventStream
     schemeIdUri="urn:scte:scte35:2014:xml+bin" 
     value="1"
     timescale="1">

    Even if the content of "value" seems irrelevant, it is configurable.

    Should a "value" field be already present in the manifest, no manipulation
    will be done.
    """

    _name = __name__

    _keys = ["value"]

    # This is just the specific ["how" config] for this plugin
    def schema(self):
        return Schema(
            {
                self._keys[0]: str
            }
        )

    def addValue(self, manifest, storage):
        for key, value in self.config(storage=storage).items():
            for period in manifest.periods:
                for eventstream in period.eventStreams:
                    if not eventstream.schemeIdValuePair.value:
                        eventstream.schemeIdValuePair = libfmp4.SchemeIdValuePair(
                            eventstream.schemeIdUri,
                            value
                        )
                    

    def process(self, manifest, storage):
        self.addValue(manifest, storage)
