import click

from ffx.model.show import Show
from ffx.show_descriptor import ShowDescriptor


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


    def getShowDescriptor(self, showId):

        try:
            s = self.Session()
            show = s.query(Show).filter(Show.id == showId).first()

            if show is not None:
                return show.getDescriptor(self.context)

        except Exception as ex:
            raise click.ClickException(f"ShowController.getShowDescriptor(): {repr(ex)}")
        finally:
            s.close()

    def getShow(self, showId):

        try:
            s = self.Session()
            return s.query(Show).filter(Show.id == showId).first()

        except Exception as ex:
            raise click.ClickException(f"ShowController.getShow(): {repr(ex)}")
        finally:
            s.close()

    def getAllShows(self):

        try:
            s = self.Session()
            return s.query(Show).all()

        except Exception as ex:
            raise click.ClickException(f"ShowController.getAllShows(): {repr(ex)}")
        finally:
            s.close()


    def updateShow(self, showDescriptor: ShowDescriptor):

        try:
            s = self.Session()
            currentShow = s.query(Show).filter(Show.id == showDescriptor.getId()).first()

            if currentShow is None:
                show = Show(id = int(showDescriptor.getId()),
                        name = str(showDescriptor.getName()),
                        year = int(showDescriptor.getYear()),
                        index_season_digits = showDescriptor.getIndexSeasonDigits(),
                        index_episode_digits = showDescriptor.getIndexEpisodeDigits(),
                        indicator_season_digits = showDescriptor.getIndicatorSeasonDigits(),
                        indicator_episode_digits = showDescriptor.getIndicatorEpisodeDigits(),
                        quality = showDescriptor.getQuality(),
                        notes = showDescriptor.getNotes())

                s.add(show)
                s.commit()
                return True
            else:
                changed = False
                if currentShow.name != str(showDescriptor.getName()):
                    currentShow.name = str(showDescriptor.getName())
                    changed = True
                if currentShow.year != int(showDescriptor.getYear()):
                    currentShow.year = int(showDescriptor.getYear())
                    changed = True

                if currentShow.index_season_digits != int(showDescriptor.getIndexSeasonDigits()):
                    currentShow.index_season_digits = int(showDescriptor.getIndexSeasonDigits())
                    changed = True
                if currentShow.index_episode_digits != int(showDescriptor.getIndexEpisodeDigits()):
                    currentShow.index_episode_digits = int(showDescriptor.getIndexEpisodeDigits())
                    changed = True
                if currentShow.indicator_season_digits != int(showDescriptor.getIndicatorSeasonDigits()):
                    currentShow.indicator_season_digits = int(showDescriptor.getIndicatorSeasonDigits())
                    changed = True
                if currentShow.indicator_episode_digits != int(showDescriptor.getIndicatorEpisodeDigits()):
                    currentShow.indicator_episode_digits = int(showDescriptor.getIndicatorEpisodeDigits())
                    changed = True
                if int(currentShow.quality or 0) != int(showDescriptor.getQuality()):
                    currentShow.quality = int(showDescriptor.getQuality())
                    changed = True
                if str(currentShow.notes or '') != str(showDescriptor.getNotes()):
                    currentShow.notes = str(showDescriptor.getNotes())
                    changed = True

                if changed:
                    s.commit()
                return changed

        except Exception as ex:
            raise click.ClickException(f"ShowController.updateShow(): {repr(ex)}")
        finally:
            s.close()


    def deleteShow(self, show_id):
        try:
            s = self.Session()
            show = s.query(Show).filter(Show.id == int(show_id)).first()

            if show is not None:

                #DAFUQ: https://stackoverflow.com/a/19245058
                # q.delete()
                s.delete(show)

                s.commit()
                return True
            return False

        except Exception as ex:
            raise click.ClickException(f"ShowController.deleteShow(): {repr(ex)}")
        finally:
            s.close()
