import pytest
import os
from calculate.utils.package import Package, PackageAtomParser,\
                                    PackageAtomError, Version,\
                                    PackageNotFound, ContentsParser
from collections import OrderedDict
from calculate.utils.files import join_paths
from pprint import pprint


CHROOT_PATH = os.path.join(os.getcwd(), 'tests/utils/testfiles/')


package_atom = PackageAtomParser(chroot_path=CHROOT_PATH)


@pytest.mark.package_utils
class TestContents:
    def test_if_two_Version_objects_compared_using_lt_operation_and_the_left_version_value_is_less_than_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('12.5.6-r1')
        version_2 = Version('12.7.6')
        assert version_1 < version_2

    def test_if_two_Version_objects_compared_using_le_operation_and_the_left_version_value_is_less_than_or_equal_to_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('3.9.0_beta')
        version_2 = Version('3.9')
        version_3 = Version('3.9.0')
        assert (version_1 <= version_2 and version_2 <= version_3)

    def test_if_two_Version_objects_compared_using_lt_operation_both_versions_has_suffixes_and_the_left_version_value_is_less_than_or_equal_to_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('13.9_alpha')
        version_2 = Version('13.9.0_beta')
        assert version_1 < version_2

    def test_if_two_Version_objects_compared_using_gt_operation_and_the_left_version_value_is_less_than_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('3.5.6-r1')
        version_2 = Version('2.5.6-r2')
        assert version_1 > version_2

    def test_if_two_Version_objects_compared_using_gt_operation_both_of_the_versions_have_revision_values_and_the_same_version_number_and_the_right_version_value_is_less_than_the_left_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('3.5.6-r2')
        version_2 = Version('3.5.6-r1')
        assert version_1 > version_2

    def test_if_two_Version_objects_compared_using_gt_operation_both_of_them_have_p_suffix_and_the_right_version_value_is_less_than_left_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('-2.5.6_p2-r1')
        version_2 = Version('2.5.6_p1-r1')
        assert version_1 > version_2

    def test_if_two_Version_objects_compared_using_ge_operation_and_the_left_version_value_is_less_than_or_equal_to_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('13.0')
        version_2 = Version('12.7.6-r1')
        assert version_1 >= version_2 and version_2 >= '12.7.6'

    def test_if_two_Version_objects_compared_using_ne_operation_and_the_left_version_value_is_less_than_or_equal_to_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('13.0')
        assert (version_1 != '12.7.6')

    def test_if_two_Version_objects_compared_using_eq_operation_and_the_left_version_value_is_less_than_or_equal_to_the_right_version__the_result_of_the_comparing_would_be_True(self):
        version_1 = Version('13.1.0')
        assert (version_1 == '13.1')

    def test_if_version_object_is_checked_to_be_in_the_range_and_the_version_is_in_the_range_indeed__the_operation_returns_True(self):
        version = Version('5.1.2')
        assert version >> ('5.1.0', '6.1.12')

    def test_if_version_object_is_checked_to_be_in_the_range_between_two_versions_values_the_first_one_is_included_and_the_version_is_in_this_range_indeed__the_operation_returns_True(self):
        version = Version('5.1.2')
        assert version >> ('=5.1.2', '6.1.12')

    def test_i_am_too_lazy_to_come_up_with_the_name_for_this_test(self):
        version = Version('5.1.2')
        assert not version >> ('5.1.2', '6.1.12')

    def test_the_same_situation(self):
        version = Version('4.1')
        assert not version >> ('5.1.2', '6.1.12')

    def test_version_representation(self):
        version_1 = Version('-2.5.6_p2-r1')
        assert str(version_1) == '2.5.6_p2-r1'

    def test_if_ContentsParser_is_used_for_parsing_of_a_correct_contents_file_text_and_then_is_used_to_get_text_of_the_source_text__the_source_text_and_the_parser_s_output_will_be_the_same(self):
        parser = ContentsParser()
        contents_text = '''dir /usr
dir /usr/bin
sym /usr/bin/rview -> vim 1573538053
sym /usr/bin/rvim -> vim 1573538053
obj /usr/bin/vim 30acc0f256e11c1ecdb1bd80b688d238 1573538056
sym /usr/bin/vimdiff -> vim 1573538053
dir /etc
dir /etc/test_dir_1
'''
        output_dict = parser.parse(contents_text)
        print('DICT:')
        pprint(output_dict)

        output_text = parser.render(output_dict)
        print('TEXT:')
        print(output_text)

        assert output_text == contents_text

    def test_if_PackageContents_object_initialized_by_existing_package__it_contains_dictionary_of_items_from_contents_file(self):
        result = OrderedDict({
                        '/usr':
                        OrderedDict({'type': 'dir'}),
                        '/usr/bin':
                        OrderedDict({'type': 'dir'}),
                        '/usr/bin/rview':
                        OrderedDict({'type': 'sym',
                                     'target': 'vim',
                                     'mtime': '1573538053'}),
                        '/usr/bin/rvim':
                        OrderedDict({'type': 'sym',
                                     'target': 'vim',
                                     'mtime': '1573538053'}),
                        '/usr/bin/vim':
                        OrderedDict({'type': 'obj',
                                     'md5': '30acc0f256e11c1ecdb1bd80b688d238',
                                     'mtime': '1573538056'}),
                        '/usr/bin/vimdiff':
                        OrderedDict({'type': 'sym',
                                     'target': 'vim',
                                     'mtime': '1573538053'})})
        contents_object = Package('category-1/package-name-1.0',
                                  chroot_path=CHROOT_PATH)
        assert contents_object.contents_dictionary == result

    def test_if_PackageContents_object_contains_contents_dictionary__it_renders_CONTENTS_file_correctly(self):
        contents_object = Package('category-1/package-name-1.0',
                                  chroot_path=CHROOT_PATH)
        result = '''dir /usr
dir /usr/bin
sym /usr/bin/rview -> vim 1573538053
sym /usr/bin/rvim -> vim 1573538053
obj /usr/bin/vim 30acc0f256e11c1ecdb1bd80b688d238 1573538056
sym /usr/bin/vimdiff -> vim 1573538053
'''
        assert contents_object.render_contents_file() == result

    def test_if_new_directory_is_added_in_contents_file_using_add_dir_method__the_PackageContents_object_renders_the_contents_file_with_new_dir(self):
        contents_object = Package('category-1/package-name-1.0',
                                  chroot_path=CHROOT_PATH)
        result = '''dir /usr
dir /usr/bin
sym /usr/bin/rview -> vim 1573538053
sym /usr/bin/rvim -> vim 1573538053
obj /usr/bin/vim 30acc0f256e11c1ecdb1bd80b688d238 1573538056
sym /usr/bin/vimdiff -> vim 1573538053
dir /etc
dir /etc/test_dir_1
'''
        contents_object.add_dir('/etc/test_dir_1')
        assert contents_object.render_contents_file() == result

    def test_if_new_object_is_added_in_contents_file_using_add_obj_method__the_PackageContents_object_renders_the_contents_file_with_new_obj(self):
        contents_object = Package('category-1/package-name-1.0',
                                  chroot_path=CHROOT_PATH)
        result = '''dir /usr
dir /usr/bin
sym /usr/bin/rview -> vim 1573538053
sym /usr/bin/rvim -> vim 1573538053
obj /usr/bin/vim 30acc0f256e11c1ecdb1bd80b688d238 1573538056
sym /usr/bin/vimdiff -> vim 1573538053
dir /etc
dir /etc/test_dir_2
obj /etc/test_dir_2/file_2.cfg a371f4d456d471ac0ed0e8befff1cb6d {}
'''.format(int(os.lstat(os.path.join(CHROOT_PATH,
                                     'etc/test_dir_2/file_2.cfg')).st_mtime))

        contents_object.add_obj('/etc/test_dir_2/file_2.cfg')
        print('RESULT:')
        print(contents_object.render_contents_file())
        assert contents_object.render_contents_file() == result

    def test_if_new_link_is_added_in_contents_file_using_add_sym_method__the_PackageContents_object_renders_the_contents_file_with_new_sym(self):
        contents_object = Package('category-1/package-name-1.0',
                                  chroot_path=CHROOT_PATH)
        result = '''dir /usr
dir /usr/bin
sym /usr/bin/rview -> vim 1573538053
sym /usr/bin/rvim -> vim 1573538053
obj /usr/bin/vim 30acc0f256e11c1ecdb1bd80b688d238 1573538056
sym /usr/bin/vimdiff -> vim 1573538053
dir /etc
dir /etc/test_dir_2
sym /etc/test_dir_2/symlink -> file_2.cfg {}
'''.format(int(os.lstat(os.path.join(CHROOT_PATH,
                                     'etc/test_dir_2/symlink')).st_mtime))

        contents_object.add_sym('/etc/test_dir_2/symlink')
        print('RESULT:')
        print(contents_object.render_contents_file())
        assert contents_object.render_contents_file() == result

    def test_if_the_PackageAtom_object_parsed_a_correct_package_atom_name_but_without_a_slot_and_use_flags__the_PackageAtom_object_returns_atom_name_of_package(self):
        atom_name = package_atom.parse_package_parameter(
                                                       'dev-lang/python-3.6.9')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                                 CHROOT_PATH,
                                 '/var/db/pkg/dev-lang/python-3.6.9'))

    def test_if_the_PackageAtom_object_parsed_a_correct_package_atom_name_with_a_slot_value__the_PackageAtom_returns_atom_name_of_package_with_this_slot(self):
        atom_name = package_atom.parse_package_parameter(
                                                'dev-lang/python-3.6:3.6/3.6m')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9') and
                atom_name.slot == '3.6/3.6m')

    def test_if_the_PackageAtom_object_parsed_a_correct_package_atom_name_with_an_empty_slot_value__the_PackageAtom_object_returns_atom_name_of_package(self):
        atom_name = package_atom.parse_package_parameter(
                                                        'dev-lang/python-3.6:')
        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9'))

    def test_if_the_PackageAtom_object_parsed_a_correct_package_atom_name_with_a_uses_value__the_PackageAtom_object_returns_atom_name_of_package_with_this_use_flags(self):
        atom_name = package_atom.parse_package_parameter(
                                        'dev-lang/python-3.6[abi_x86_64,ssl]')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9') and
                'abi_x86_64' in atom_name.use_flags and
                'ssl' in atom_name.use_flags)

    def test_if_the_PackageAtom_object_parses_a_correct_package_atom_name_without_version_value_but_with_slot_value__the_PackageAtom_object_looks_for_package_with_assigned_slot_value(self):
        atom_name = package_atom.parse_package_parameter(
                                                    'dev-lang/python:3.6/3.6m')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9') and
                atom_name.slot == '3.6/3.6m')

    def test_if_the_PackageAtom_object_parses_a_correct_package_atom_name_without_version_value_but_with_use_flags_value__the_PackageAtom_object_looks_for_package_with_assigned_use_flags(self):
        atom_name = package_atom.parse_package_parameter(
                                             'dev-lang/python[specific_flag]')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9') and
                'specific_flag' in atom_name.use_flags)

    def test_if_the_PackageAtom_object_tried_to_parse_an_incorrect_package_atom_name__the_PackageAtom_object_throws_the_PackageAtomError_exception(self):
        with pytest.raises(PackageAtomError):
            package_atom.parse_package_parameter(
                                'dev-lang/something_i_can_never_have:3.6/3.6m')

    def test_if_the_PackageAtom_object_tried_to_parse_an_package_atom_name_with_incorrect_use_flags__the_PackageAtom_object_throws_the_PackageAtomError_exception(self):
        with pytest.raises(PackageAtomError):
            package_atom.parse_package_parameter(
                                               'dev-lang/python[strange_use]')

    def test_if_the_PackageAtom_object_tried_to_parse_an_correct_package_atom_name_that_matches_multiple_packages__the_PackageAtom_object_gets_info_for_package_with_older_version(self):
        atom_name = package_atom.parse_package_parameter('dev-lang/python')

        assert (atom_name.category == 'dev-lang' and
                atom_name.fullname == 'python-3.6.9' and
                atom_name.version == Version('3.6.9') and
                atom_name.pkg_path == join_paths(
                             CHROOT_PATH,
                             '/var/db/pkg/dev-lang/python-3.6.9'))

    def test_if_the_get_file_package_method_of_the_PackageAtom_object_is_called_with_a_name_of_a_file_that_belongs_to_any_package__the_PackageAtom_object_contains_dictionary_with_an_owner_package(self):
        try:
            package_atom_name = package_atom.get_file_package('/usr/bin/python3.6')
            assert package_atom_name.version > '2.7.16'
        except Exception as error:
            pytest.fail('Unexpected exception: {0}'.
                        format(str(error)))

    def test_if_the_get_file_package_method_of_the_PackageAtom_object_is_called_with_a_name_of_a_file_that_does_not_belong_to_any_package__the_PackageAtom_object_throws_the_PackageAtomError_exception(self):
        with pytest.raises(PackageNotFound):
            file_package = package_atom.get_file_package('/etc/shadow')
            print('package = {}'.format(file_package))
