# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2019 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/>.

from urllib import parse as urlparse

import pytest
import requests


def test_wcs_fixture(wcs_host):
    assert wcs_host.url.startswith('http://127.0.0.1:')
    requests.get(wcs_host.url)
    response = requests.get(urlparse.urljoin(wcs_host.url, '/api/categories/'))
    assert response.json()['data'][0]['title'] == 'Catégorie'


def test_wcs_api(wcs_host):
    from passerelle.utils.wcs import WcsApiError

    api = wcs_host.api
    assert len(api.categories) == 1
    assert len(api.formdefs) == 1
    assert len(api.roles) == 1
    formdef = api.formdefs['demande']

    assert formdef.schema.fields[4].label == '5th field'
    assert len(formdef.formdatas) == 10
    assert len(formdef.formdatas.full) == 10
    formdata = next(iter(formdef.formdatas))
    assert formdata is not formdata.full
    assert formdata.full is formdata.full
    assert formdata.full.full is formdata.full
    assert formdata.full.anonymized is not formdata.full

    with formdef.submit() as submitter:
        with pytest.raises(ValueError):
            submitter.set('zob', '1')
        submitter.draft = True
        submitter.submission_channel = 'mdel'
        submitter.submission_context = {
            'mdel_ref': 'ABCD',
        }
        submitter.set('string', 'hello')
        submitter.set('item', 'foo')
        submitter.set('item_open', {'id': '1', 'text': 'world', 'foo': 'bar'})
        submitter.set(
            'item_datasource',
            {
                'id': '2',
                'text': 'world',
            },
        )

    formdata = formdef.formdatas[submitter.result.id]
    api = wcs_host.anonym_api

    assert len(api.categories) == 1
    assert len(api.formdefs) == 1
    assert len(api.roles) == 1
    formdef = api.formdefs['demande']
    assert formdef.schema.fields[4].label == '5th field'
    with pytest.raises(WcsApiError):
        assert len(formdef.formdatas) == 10
    assert len(formdef.formdatas.anonymized) == 10
