import datetime
import pytest

from aircox.conf import settings
from aircox import models


class TestEpisode:
    @pytest.mark.django_db
    def test_program(self, episode):
        assert episode.program == episode.parent.program

    @pytest.mark.django_db
    def test_podcasts(self, episode, podcasts):
        podcasts = {podcast.pk: podcast for podcast in podcasts if podcast.episode == episode}
        for data in episode.podcasts:
            podcast = podcasts[data["pk"]]
            assert data["name"] == podcast.name
            assert data["page_url"] == episode.get_absolute_url()
            assert data["page_title"] == episode.title

    @pytest.mark.django_db
    def test_get_absolute_url_is_published(self, episode):
        episode.status = models.Episode.STATUS_PUBLISHED
        assert episode.get_absolute_url() != episode.parent.get_absolute_url()

    @pytest.mark.django_db
    def test_get_absolute_url_not_published(self, episode):
        episode.status = models.Episode.STATUS_DRAFT
        assert episode.get_absolute_url() == episode.parent.get_absolute_url()

    @pytest.mark.django_db(transaction=False)
    def test_save_raises_parent_is_none(self, episode):
        with pytest.raises(ValueError):
            episode.parent = None
            episode.save()

    @pytest.mark.django_db
    def test_get_default_title(self, programs):
        program = programs[0]
        date = datetime.date(2023, 5, 17)
        result = models.Episode.get_default_title(program, date)
        assert program.title in result
        assert date.strftime(settings.EPISODE_TITLE_DATE_FORMAT) in result

    @pytest.mark.django_db
    def test_get_init_kwargs_from(self, program):
        date = datetime.date(2023, 3, 14)
        date_str = date.strftime(settings.EPISODE_TITLE_DATE_FORMAT)

        kwargs = models.Episode.get_init_kwargs_from(program, date)
        title = kwargs["title"]
        assert program.title in title
        assert date_str in title

    @pytest.mark.django_db
    def test_get_init_kwargs_from_with_title(self, program):
        title = "test title"
        kwargs = models.Episode.get_init_kwargs_from(program, title=title)
        assert title == kwargs["title"]
