# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2021 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os

import pytest
import xmlschema

from passerelle.contrib.caluire_axel.schemas import CaluireAxelSchema

XSD_BASE_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), '../passerelle/contrib/caluire_axel/xsd'
)


@pytest.mark.parametrize('bool_type', ['ONType', 'ONEmptyType'])
@pytest.mark.parametrize(
    'value, expected, py_expected',
    [
        ('O', 'O', True),
        ('o', 'O', True),
        ('TRUE', 'O', True),
        ('true', 'O', True),
        ('True', 'O', True),
        (True, 'O', True),
        ('1', 'O', True),
        ('N', 'N', False),
        ('n', 'N', False),
        ('FALSE', 'N', False),
        ('false', 'N', False),
        ('False', 'N', False),
        (False, 'N', False),
        ('0', 'N', False),
        ('FOOBAR', 'FOOBAR', None),
        ('42', '42', None),
        ('OUIFOOBAR', 'OUIFOOBAR', None),
        ('FOONONBAR', 'FOONONBAR', None),
    ],
)
def test_bool_mapping(bool_type, value, expected, py_expected):
    if expected == '' and bool_type == 'ONType':
        # required, can't be empty
        return

    xsd = """<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:all="urn:AllAxelTypes">
    <xsd:import schemaLocation="{path}/AllAxelTypes.xsd" namespace="urn:AllAxelTypes"  />
    <xsd:complexType name="PORTAILType">
        <xsd:sequence>
            <xsd:element name="BOOL" type="all:{bool_type}"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:element name="PORTAIL" type="PORTAILType"/>
</xsd:schema>""".format(
        path=XSD_BASE_DIR, bool_type=bool_type
    )

    schema = CaluireAxelSchema(xsd, 'PORTAIL')

    if py_expected is None:
        with pytest.raises(xmlschema.XMLSchemaValidationError):
            xml_data = schema.encode({'PORTAIL': {'BOOL': value}})
            assert xml_data.find('BOOL').text == expected
            schema.decode(xml_data)
    else:
        xml_data = schema.encode({'PORTAIL': {'BOOL': value}})
        assert xml_data.find('BOOL').text == expected
        json_data = schema.decode(xml_data)
        assert json_data['BOOL'] is py_expected
