from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase
import os
from tests.util import maketemp


class TestExistsSeries(FlexGetBase):

    __yaml__ = """
        tasks:
          test:
            mock:
              - {title: 'Foo.Bar.S01E02.XViD'}
              - {title: 'Foo.Bar.S01E03.XViD'}
            series:
              - foo bar
            exists_series:
              path: autogenerated in setup()

          test_diff_qualities_allowed:
            mock:
              - {title: 'Asdf.S01E02.720p'}
            series:
              - asdf
            exists_series:
              path:  path autogenerated in setup()
              allow_different_qualities: yes

          test_diff_qualities_not_allowed:
            mock:
              - {title: 'Asdf.S01E02.720p'}
            series:
              - asdf
            exists_series: path autogenerated in setup()

          test_diff_qualities_downgrade:
            mock:
              - {title: 'Asdf.S01E02.sdtv'}
            series:
              - asdf
            exists_series:
              path:  path autogenerated in setup()
              allow_different_qualities: better

          test_diff_qualities_upgrade:
            mock:
              - {title: 'Asdf.S01E02.webdl'}
            series:
              - asdf
            exists_series:
              path:  path autogenerated in setup()
              allow_different_qualities: better

          test_propers:
            mock:
              - {title: 'Mock.S01E01.Proper'}
              - {title: 'Test.S01E01'}
            series:
              - mock
              - test
            exists_series: path autogenerated in setup()

          test_invalid:
            mock:
              - {title: 'Invalid.S01E01'}
            series:
              - invalid
            exists_series: path autogenerated in setup()

          test_with_metainfo_series:
            metainfo_series: yes
            mock:
              - {title: 'Foo.Bar.S01E02.XViD'}
              - {title: 'Foo.Bar.S01E03.XViD'}
            accept_all: yes
            exists_series: path autogenerated in setup()
          test_jinja_path:
            series:
            - jinja
            - jinja2
            mock:
            - title: jinja s01e01
            - title: jinja s01e02
            - title: jinja2 s01e01
            accept_all: yes
            exists_series: path autogenerated in setup()
    """

    test_dirs = ['Foo.Bar.S01E02.XViD-GrpA', 'Asdf.S01E02.HDTV', 'Mock.S01E01.XViD', 'Test.S01E01.Proper',
                 'jinja/jinja.s01e01', 'jinja.s01e02', 'jinja2/jinja2.s01e01', 'invalid']

    def __init__(self):
        self.test_home = None
        FlexGetBase.__init__(self)

    def setup(self):
        FlexGetBase.setup(self)
        # generate config
        self.test_home = maketemp()
        for task_name in self.manager.config['tasks'].iterkeys():
            if isinstance(self.manager.config['tasks'][task_name]['exists_series'], dict):
                self.manager.config['tasks'][task_name]['exists_series']['path'] = self.test_home
            else:
                self.manager.config['tasks'][task_name]['exists_series'] = self.test_home
        # create test dirs
        for test_dir in self.test_dirs:
            os.makedirs(os.path.join(self.test_home, test_dir))

    def teardown(self):
        curdir = os.getcwd()
        os.chdir(self.test_home)
        for test_dir in self.test_dirs:
            os.removedirs(test_dir)
        os.chdir(curdir)
        os.rmdir(self.test_home)
        FlexGetBase.teardown(self)

    def test_existing(self):
        """Exists_series plugin: existing"""
        self.execute_task('test')
        assert not self.task.find_entry('accepted', title='Foo.Bar.S01E02.XViD'), \
            'Foo.Bar.S01E02.XViD should not have been accepted (exists)'
        assert self.task.find_entry('accepted', title='Foo.Bar.S01E03.XViD'), \
            'Foo.Bar.S01E03.XViD should have been accepted'

    def test_diff_qualities_allowed(self):
        """Exists_series plugin: existsting but w. diff quality"""
        self.execute_task('test_diff_qualities_allowed')
        assert self.task.find_entry('accepted', title='Asdf.S01E02.720p'), \
            'Asdf.S01E02.720p should have been accepted'

    def test_diff_qualities_not_allowed(self):
        """Exists_series plugin: existsting but w. diff quality"""
        self.execute_task('test_diff_qualities_not_allowed')
        assert self.task.find_entry('rejected', title='Asdf.S01E02.720p'), \
            'Asdf.S01E02.720p should have been rejected'

    def test_diff_qualities_downgrade(self):
        """Test worse qualities than exist are rejected."""
        self.execute_task('test_diff_qualities_downgrade')
        assert self.task.find_entry('rejected', title='Asdf.S01E02.sdtv'), \
            'Asdf.S01E02.sdtv should have been rejected'

    def test_diff_qualities_upgrade(self):
        """Test better qualities than exist are accepted."""
        self.execute_task('test_diff_qualities_upgrade')
        assert self.task.find_entry('accepted', title='Asdf.S01E02.webdl'), \
            'Asdf.S01E02.webdl should have been rejected'

    def test_propers(self):
        """Exists_series plugin: new proper & proper already exists"""
        self.execute_task('test_propers')
        assert self.task.find_entry('accepted', title='Mock.S01E01.Proper'), \
            'new proper not accepted'
        assert self.task.find_entry('rejected', title='Test.S01E01'), \
            'pre-existin proper should have caused reject'

    def test_invalid(self):
        """Exists_series plugin: no episode numbering on the disk"""
        # shouldn't raise anything
        self.execute_task('test_invalid')

    def test_with_metainfo_series(self):
        """Tests that exists_series works with series data from metainfo_series"""
        self.execute_task('test_with_metainfo_series')
        assert self.task.find_entry('rejected', title='Foo.Bar.S01E02.XViD'), \
            'Foo.Bar.S01E02.XViD should have been rejected(exists)'
        assert not self.task.find_entry('rejected', title='Foo.Bar.S01E03.XViD'), \
            'Foo.Bar.S01E03.XViD should not have been rejected'

    def test_jinja_path(self):
        self.manager.config['tasks']['test_jinja_path']['exists_series'] += '/{{series_name}}'
        self.execute_task('test_jinja_path')
        assert self.task.find_entry('rejected', title='jinja s01e01'), \
            'jinja s01e01 should have been rejected (exists)'
        assert self.task.find_entry('rejected', title='jinja2 s01e01'), \
            'jinja2 s01e01 should have been rejected (exists)'
        assert self.task.find_entry('accepted', title='jinja s01e02'), \
            'jinja s01e02 should have been accepted'
