# -*- coding: utf-8 -*-

import datetime

import pytest
import requests_mock
from geolink_formatter.entity import Document, File
from requests.auth import HTTPBasicAuth

from pyramid_oereb.contrib.sources.document import OEREBlexSource
from pyramid_oereb.lib.records.documents import DocumentRecord, LegalProvisionRecord
from pyramid_oereb.lib.records.office import OfficeRecord
from tests.mockrequest import MockParameter


@pytest.mark.parametrize('valid,cfg', [
    (True, {
        'host': 'http://oereblex.example.com',
        'language': 'de',
        'canton': 'BL'
    }),
    (False, {
        'language': 'de',
        'canton': 'BL'
    }),
    (False, {
        'host': 'http://oereblex.example.com',
        'language': 'german',
        'canton': 'BL'
    }),
    (False, {
        'host': 'http://oereblex.example.com',
        'language': 'de'
    })
])
def test_init(valid, cfg):
    if valid:
        assert isinstance(OEREBlexSource(**cfg), OEREBlexSource)
    else:
        with pytest.raises(AssertionError):
            OEREBlexSource(**cfg)


@pytest.mark.parametrize('key,language,result', [
    ('official_title', None, None),
    ('municipality', None, 'Liestal'),
    ('municipality', 'de', {'de': 'Liestal'})
])
def test_get_mapped_value(key, language, result):
    file_ = File('Test', '/api/attachments/1', 'main')
    document = Document(id='test', title='Test', category='main', doctype='decree', files=[file_],
                        enactment_date=datetime.date.today(), subtype='Liestal', authority='Office')
    source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL',
                            mapping={'municipality': 'subtype'})
    assert source._get_mapped_value(document, key, language=language) == result


@pytest.mark.parametrize('i,document', [
    (1, Document(
        id='doc1',
        title='Document 1',
        category='main',
        doctype='edict',
        authority='Office',
        files=[File('File 1', '/api/attachments/1', 'main')],
        enactment_date=datetime.date.today()
    )),
    (2, Document(
        id='doc2',
        title='Document 2',
        category='main',
        doctype='decree',
        authority='Office',
        files=[
            File('File 2', '/api/attachments/2', 'main'),
            File('File 3', '/api/attachments/3', 'additional')
        ],
        enactment_date=datetime.date.today()
    )),
    (3, Document(
        id='doc1',
        title='Document 1',
        category='main',
        doctype='invalid',
        authority='Office',
        files=[File('File 1', '/api/attachments/1', 'main')],
        enactment_date=datetime.date.today()
    )),
    (4, Document(
        id='doc1',
        title='Document 1',
        category='main',
        doctype='decree',
        authority='Office',
        files=[],
        enactment_date=datetime.date.today()
    ))
])
def test_get_document_records(i, document):
    language = 'de'
    source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL')
    references = [
        Document(
            id='ref',
            title='Reference',
            category='related',
            doctype='edict',
            authority='Office',
            files=[File('Reference file', '/api/attachments/4', 'main')],
            enactment_date=datetime.date.today()
        )
    ]

    if i == 3:
        with pytest.raises(TypeError):
            source._get_document_records(document, language, references)
    elif i == 4:
        assert source._get_document_records(document, language, references) == []
    else:
        records = source._get_document_records(document, language, references)
        assert len(records) == i
        for idx, record in enumerate(records):
            if i == 1:
                assert isinstance(record, DocumentRecord)
            elif i == 2:
                assert isinstance(record, LegalProvisionRecord)
            assert record.title == {'de': 'Document {0}'.format(i)}
            assert record.published_from == datetime.date.today()
            assert record.canton == 'BL'
            assert record.text_at_web == {'de': '/api/attachments/{fid}'.format(fid=i + idx)}
            assert len(record.references) == 1
            reference = record.references[0]
            assert isinstance(reference, DocumentRecord)
            assert reference.title == {'de': 'Reference'}
            assert reference.canton == 'BL'
            assert reference.text_at_web == {'de': '/api/attachments/4'}


def test_read():
    with requests_mock.mock() as m:
        with open('./tests/resources/geolink_v1.1.1.xml', 'rb') as f:
            m.get('http://oereblex.example.com/api/geolinks/100.xml', content=f.read())
        source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL')
        source.read(MockParameter(), 100)
        assert len(source.records) == 2
        document = source.records[0]
        assert isinstance(document, DocumentRecord)
        assert isinstance(document.responsible_office, OfficeRecord)
        assert document.responsible_office.name == {'de': 'Landeskanzlei'}
        assert document.canton == 'BL'
        assert document.text_at_web == {
            'de': 'http://oereblex.example.com/api/attachments/313'
        }
        assert len(document.references) == 5


def test_read_related_decree_as_main():
    with requests_mock.mock() as m:
        with open('./tests/resources/geolink_v1.1.1.xml', 'rb') as f:
            m.get('http://oereblex.example.com/api/geolinks/100.xml', content=f.read())
        source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL',
                                related_decree_as_main=True)
        source.read(MockParameter(), 100)
        assert len(source.records) == 3
        document = source.records[0]
        assert isinstance(document, DocumentRecord)
        assert isinstance(document.responsible_office, OfficeRecord)
        assert document.responsible_office.name == {'de': 'Landeskanzlei'}
        assert document.canton == 'BL'
        assert document.text_at_web == {
            'de': 'http://oereblex.example.com/api/attachments/313'
        }
        assert len(document.references) == 4


def test_read_with_version_in_url():
    with requests_mock.mock() as m:
        with open('./tests/resources/geolink_v1.1.1.xml', 'rb') as f:
            m.get('http://oereblex.example.com/api/1.1.1/geolinks/100.xml', content=f.read())
        source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL',
                                pass_version=True)
        source.read(MockParameter(), 100)
        assert len(source.records) == 2


def test_read_with_specified_version():
    with requests_mock.mock() as m:
        with open('./tests/resources/geolink_v1.0.0.xml', 'rb') as f:
            m.get('http://oereblex.example.com/api/1.0.0/geolinks/100.xml', content=f.read())
        source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL',
                                pass_version=True, version='1.0.0')
        source.read(MockParameter(), 100)
        assert len(source.records) == 2


def test_read_with_specified_language():
    with requests_mock.mock() as m:
        with open('./tests/resources/geolink_v1.1.1.xml', 'rb') as f:
            m.get('http://oereblex.example.com/api/geolinks/100.xml?locale=fr', content=f.read())
        source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL')
        params = MockParameter()
        params.set_language('fr')
        source.read(params, 100)
        assert len(source.records) == 2
        document = source.records[0]
        assert document.responsible_office.name == {'fr': 'Landeskanzlei'}
        assert document.text_at_web == {
            'fr': 'http://oereblex.example.com/api/attachments/313'
        }


def test_authentication():
    auth = {
        'username': 'test',
        'password': 'test'
    }
    source = OEREBlexSource(host='http://oereblex.example.com', language='de', canton='BL', auth=auth)
    assert isinstance(source._auth, HTTPBasicAuth)


def test_get_document_title():
    document = Document([], id='1', title='Test')
    result = {'de': 'Test'}
    assert OEREBlexSource._get_document_title(document, File(), 'de') == result

[((16, 1, 35, 2), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(16, 25, 16, 36): '"""valid,cfg"""', (16, 38, 35, 1): "[(True, {'host': 'http://oereblex.example.com', 'language': 'de', 'canton':\n    'BL'}), (False, {'language': 'de', 'canton': 'BL'}), (False, {'host':\n    'http://oereblex.example.com', 'language': 'german', 'canton': 'BL'}),\n    (False, {'host': 'http://oereblex.example.com', 'language': 'de'})]"}, {}), "('valid,cfg', [(True, {'host':\n    'http://oereblex.example.com', 'language': 'de', 'canton': 'BL'}), (\n    False, {'language': 'de', 'canton': 'BL'}), (False, {'host':\n    'http://oereblex.example.com', 'language': 'german', 'canton': 'BL'}),\n    (False, {'host': 'http://oereblex.example.com', 'language': 'de'})])", False, 'import pytest\n'), ((44, 1, 48, 2), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(44, 25, 44, 46): '"""key,language,result"""', (44, 48, 48, 1): "[('official_title', None, None), ('municipality', None, 'Liestal'), (\n    'municipality', 'de', {'de': 'Liestal'})]"}, {}), "('key,language,result', [('official_title', None,\n    None), ('municipality', None, 'Liestal'), ('municipality', 'de', {'de':\n    'Liestal'})])", False, 'import pytest\n'), ((50, 12, 50, 54), 'geolink_formatter.entity.File', 'File', ({(50, 17, 50, 23): '"""Test"""', (50, 25, 50, 45): '"""/api/attachments/1"""', (50, 47, 50, 53): '"""main"""'}, {}), "('Test', '/api/attachments/1', 'main')", False, 'from geolink_formatter.entity import Document, File\n'), ((53, 13, 54, 64), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((101, 13, 101, 91), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((217, 13, 217, 102), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((222, 15, 222, 49), 'geolink_formatter.entity.Document', 'Document', (), '', False, 'from geolink_formatter.entity import Document, File\n'), ((140, 9, 140, 29), 'requests_mock.mock', 'requests_mock.mock', ({}, {}), '()', False, 'import requests_mock\n'), ((143, 17, 143, 95), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((158, 9, 158, 29), 'requests_mock.mock', 'requests_mock.mock', ({}, {}), '()', False, 'import requests_mock\n'), ((161, 17, 162, 60), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((177, 9, 177, 29), 'requests_mock.mock', 'requests_mock.mock', ({}, {}), '()', False, 'import requests_mock\n'), ((180, 17, 181, 50), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((187, 9, 187, 29), 'requests_mock.mock', 'requests_mock.mock', ({}, {}), '()', False, 'import requests_mock\n'), ((190, 17, 191, 67), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((197, 9, 197, 29), 'requests_mock.mock', 'requests_mock.mock', ({}, {}), '()', False, 'import requests_mock\n'), ((200, 17, 200, 95), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', (), '', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((201, 17, 201, 32), 'tests.mockrequest.MockParameter', 'MockParameter', ({}, {}), '()', False, 'from tests.mockrequest import MockParameter\n'), ((38, 26, 38, 47), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', ({}, {}), '(**cfg)', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((40, 13, 40, 42), 'pytest.raises', 'pytest.raises', ({(40, 27, 40, 41): 'AssertionError'}, {}), '(AssertionError)', False, 'import pytest\n'), ((41, 12, 41, 33), 'pyramid_oereb.contrib.sources.document.OEREBlexSource', 'OEREBlexSource', ({}, {}), '(**cfg)', False, 'from pyramid_oereb.contrib.sources.document import OEREBlexSource\n'), ((52, 39, 52, 60), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((115, 13, 115, 37), 'pytest.raises', 'pytest.raises', ({(115, 27, 115, 36): 'TypeError'}, {}), '(TypeError)', False, 'import pytest\n'), ((144, 20, 144, 35), 'tests.mockrequest.MockParameter', 'MockParameter', ({}, {}), '()', False, 'from tests.mockrequest import MockParameter\n'), ((163, 20, 163, 35), 'tests.mockrequest.MockParameter', 'MockParameter', ({}, {}), '()', False, 'from tests.mockrequest import MockParameter\n'), ((182, 20, 182, 35), 'tests.mockrequest.MockParameter', 'MockParameter', ({}, {}), '()', False, 'from tests.mockrequest import MockParameter\n'), ((192, 20, 192, 35), 'tests.mockrequest.MockParameter', 'MockParameter', ({}, {}), '()', False, 'from tests.mockrequest import MockParameter\n'), ((224, 56, 224, 62), 'geolink_formatter.entity.File', 'File', ({}, {}), '()', False, 'from geolink_formatter.entity import Document, File\n'), ((110, 27, 110, 48), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((109, 19, 109, 71), 'geolink_formatter.entity.File', 'File', ({(109, 24, 109, 40): '"""Reference file"""', (109, 42, 109, 62): '"""/api/attachments/4"""', (109, 64, 109, 70): '"""main"""'}, {}), "('Reference file', '/api/attachments/4', 'main')", False, 'from geolink_formatter.entity import Document, File\n'), ((128, 44, 128, 65), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((66, 23, 66, 44), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((78, 23, 78, 44), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((87, 23, 87, 44), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((96, 23, 96, 44), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((65, 15, 65, 59), 'geolink_formatter.entity.File', 'File', ({(65, 20, 65, 28): '"""File 1"""', (65, 30, 65, 50): '"""/api/attachments/1"""', (65, 52, 65, 58): '"""main"""'}, {}), "('File 1', '/api/attachments/1', 'main')", False, 'from geolink_formatter.entity import Document, File\n'), ((75, 12, 75, 56), 'geolink_formatter.entity.File', 'File', ({(75, 17, 75, 25): '"""File 2"""', (75, 27, 75, 47): '"""/api/attachments/2"""', (75, 49, 75, 55): '"""main"""'}, {}), "('File 2', '/api/attachments/2', 'main')", False, 'from geolink_formatter.entity import Document, File\n'), ((76, 12, 76, 62), 'geolink_formatter.entity.File', 'File', ({(76, 17, 76, 25): '"""File 3"""', (76, 27, 76, 47): '"""/api/attachments/3"""', (76, 49, 76, 61): '"""additional"""'}, {}), "('File 3', '/api/attachments/3', 'additional')", False, 'from geolink_formatter.entity import Document, File\n'), ((86, 15, 86, 59), 'geolink_formatter.entity.File', 'File', ({(86, 20, 86, 28): '"""File 1"""', (86, 30, 86, 50): '"""/api/attachments/1"""', (86, 52, 86, 58): '"""main"""'}, {}), "('File 1', '/api/attachments/1', 'main')", False, 'from geolink_formatter.entity import Document, File\n')]