import click

from ffx.model.pattern import Pattern
from ffx.media_descriptor import MediaDescriptor

from ffx.tag_controller import TagController
from ffx.track_controller import TrackController

class MediaController():
    
    def __init__(self, context):
        
        self.context = context
        self.Session = self.context['database']['session'] # convenience

        self.__logger = context['logger']

        self.__tc = TrackController(context = context)
        self.__tac = TagController(context = context)

    def setPatternMediaDescriptor(self, mediaDescriptor: MediaDescriptor, patternId: int):

        try:

            pid = int(patternId)

            s = self.Session()
            pattern = s.query(Pattern).filter(Pattern.id == pid).first()

            if pattern is not None:

                for mediaTagKey, mediaTagValue in mediaDescriptor.getTags():
                    self.__tac.updateMediaTag(pid, mediaTagKey, mediaTagValue)
                # for trackDescriptor in mediaDescriptor.getAllTrackDescriptors():
                for trackDescriptor in mediaDescriptor.getTrackDescriptors():
                    self.__tc.addTrack(trackDescriptor, patternId = pid)

                s.commit()
                return True
            else:
                return False

        except Exception as ex:
            self.__logger.error(f"MediaController.setPatternMediaDescriptor(): {repr(ex)}")
            raise click.ClickException(f"MediaController.setPatternMediaDescriptor(): {repr(ex)}")
        finally:
            s.close()
