import click

from sqlalchemy import Column, Integer, String, Text, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship

from .show import Base, Show

from ffx.media_descriptor import MediaDescriptor
from ffx.show_descriptor import ShowDescriptor


class Pattern(Base):

    __tablename__ = 'patterns'
    __table_args__ = (
        UniqueConstraint('show_id', 'pattern', name='uq_patterns_show_id_pattern'),
    )

    # v1.x
    id = Column(Integer, primary_key=True)
    pattern = Column(String)

    # v2.0
    # id: Mapped[int] = mapped_column(Integer, primary_key=True)
    # pattern: Mapped[str] = mapped_column(String, nullable=False)

    # v1.x
    show_id = Column(Integer, ForeignKey('shows.id', ondelete="CASCADE"))
    show = relationship(Show, back_populates='patterns', lazy='joined')

    # v2.0
    # show_id: Mapped[int] = mapped_column(ForeignKey("shows.id", ondelete="CASCADE"))
    # show: Mapped["Show"] = relationship(back_populates="patterns")

    tracks = relationship('Track', back_populates='pattern', cascade="all, delete", lazy='joined')

    media_tags = relationship('MediaTag', back_populates='pattern', cascade="all, delete", lazy='joined')
    shifted_seasons = relationship('ShiftedSeason', back_populates='pattern', cascade="all, delete", lazy='joined')

    quality = Column(Integer, default=0)

    notes = Column(Text, default='')



    def getId(self):
        return int(self.id)

    def getShowId(self):
        return int(self.show_id)

    def getShowDescriptor(self, context) -> ShowDescriptor:
        # click.echo(f"self.show {self.show} id={self.show_id}")
        return self.show.getDescriptor(context)

    def getId(self):
        return int(self.id)

    def getPattern(self):
        return str(self.pattern)

    def getTags(self):
        return {str(t.key):str(t.value) for t in self.media_tags}


    def getMediaDescriptor(self, context):

        kwargs = {}

        kwargs[MediaDescriptor.CONTEXT_KEY] = context

        kwargs[MediaDescriptor.TAGS_KEY] = self.getTags()
        kwargs[MediaDescriptor.TRACK_DESCRIPTOR_LIST_KEY] = []

        # Set ordered subindices
        subIndexCounter = {}
        for track in self.tracks:
            trackType = track.getType()
            if not trackType in subIndexCounter.keys():
                subIndexCounter[trackType] = 0
            kwargs[MediaDescriptor.TRACK_DESCRIPTOR_LIST_KEY].append(track.getDescriptor(context, subIndex = subIndexCounter[trackType]))
            subIndexCounter[trackType] += 1

        return MediaDescriptor(**kwargs)
