import click

from .filter import Filter

from ffx.video_encoder import VideoEncoder


class QualityFilter(Filter):

    IDENTIFIER = 'quality'

    DEFAULT_VP9_QUALITY = 32
    DEFAULT_H264_QUALITY = 17

    QUALITY_KEY = 'quality'

    def __init__(self, **kwargs):

        context = click.get_current_context().obj
    

        self.__qualitiesList = []
        qualities = kwargs.get(QualityFilter.QUALITY_KEY, '')
        if qualities:
            qualityTokens = qualities.split(',')
            for q in qualityTokens:
                try:
                    qualityValue = int(q)
                except:
                    raise ValueError('QualityFilter: Quality value has to be of type int')
                if qualityValue < 0 or qualityValue > 63:
                    raise ValueError('QualityFilter: Quality value has to be between 0 and 63')
                self.__qualitiesList.append(qualityValue)
        else:

            self.__qualitiesList = [None]


        super().__init__(self)


    def getPayload(self, quality):

        suffices = []

        if len(self.__qualitiesList) > 1:
            suffices += [f"q{quality}"]

        payload = {'identifier': QualityFilter.IDENTIFIER,
                   'parameters': {
                        'quality': quality
                    },
                    'suffices': suffices,
                    'variant': f"Q{quality}",
                    'tokens': []}

        return payload


    def getYield(self):
        for q in self.__qualitiesList:            
            yield self.getPayload(q)
