from __future__ import unicode_literals, division, absolute_import
import re
from datetime import datetime, timedelta
import mock
import pytest
from flexget.manager import Session
from flexget.plugins.api_tvdb import persist, TVDBSearchResult, lookup_series, mark_expired, TVDBRequest, TVDBEpisode, TVDBSeries
from flexget.plugins.input.thetvdb_favorites import TVDBUserFavorite


@mock.patch('flexget.plugins.api_tvdb.mark_expired')
@pytest.mark.online
class TestTVDBLookup(object):
    config = """
        templates:
          global:
            thetvdb_lookup: yes
            # Access a tvdb field to cause lazy loading to occur
            set:
              afield: "{{ tvdb_id }}{{ tvdb_ep_name }}"
        tasks:
          test:
            mock:
              - {title: 'House.S01E02.HDTV.XViD-FlexGet'}
              - {title: 'Breaking.Bad.S01E02.HDTV.XViD-FlexGet'}
              - {title: 'Doctor.Who.2005.S02E03.PDTV.XViD-FlexGet'}
            series:
              - House
              - Doctor Who 2005
          test_search_cache:
            mock:
              - {title: 'House.S01E02.HDTV.XViD-FlexGet'}
            series:
              - House
          test_unknown_series:
            mock:
              - {title: 'Aoeu.Htns.S01E01.htvd'}
            series:
              - Aoeu Htns
          test_date:
            mock:
              - title: the daily show 2012-6-6
            series:
              - the daily show (with jon stewart)
          test_absolute:
            mock:
              - title: naruto 128
            series:
              - naruto
          test_no_poster_actors:
            mock:
              - {title: 'Sex.House.S01E02.HDTV.XViD-FlexGet'}
            series:
              - Sex House
              - The Blacklist

    """

    def test_lookup(self, mocked_expired, execute_task):
        """thetvdb: Test Lookup (ONLINE)"""
        persist['auth_tokens'] = {'default': None}

        task = execute_task('test')

        assert task.find_entry(tvdb_ep_name='School Reunion'), 'Failed imdb lookup Doctor Who 2005 S02E03'

        entry = task.find_entry(title='House.S01E02.HDTV.XViD-FlexGet')
        assert entry['tvdb_id'] == 73255
        assert entry['tvdb_absolute_number'] == 3
        assert entry['tvdb_rating'] == 9.1
        assert entry['tvdb_runtime'] == 45
        assert entry['tvdb_season'] == 1
        assert entry['tvdb_series_name'] == 'House'
        assert entry['tvdb_status'] == 'Ended'
        assert entry['tvdb_air_time'] == ''
        assert entry['tvdb_airs_day_of_week'] == ''
        assert re.match('http://thetvdb.com/banners/graphical/73255-g[0-9]+.jpg', entry['tvdb_banner'])
        assert 'http://thetvdb.com/banners/posters/73255-1.jpg' in entry['tvdb_posters']
        assert entry['tvdb_content_rating'] == 'TV-14'
        assert entry['tvdb_episode'] == 2
        assert entry['tvdb_first_air_date'] == datetime(2004, 11, 16, 0, 0)
        assert entry['tvdb_network'] == 'FOX (US)'