# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2022  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 contextlib
import os.path
import pathlib
import socket

import pytest
from ldaptools.slapd import Slapd, has_slapd

pytestmark = pytest.mark.skipif(not has_slapd(), reason='slapd is not installed')

base_dir = os.path.dirname(__file__)
cert_file = os.path.join(base_dir, 'cert.pem')
key_file = os.path.join(base_dir, 'key.pem')


@pytest.fixture
def cert():
    return pathlib.Path(cert_file)


@pytest.fixture
def key():
    return pathlib.Path(key_file)


@pytest.fixture
def cert_content(cert):
    with cert.open(mode='rb') as fd:
        return fd.read()


@pytest.fixture
def key_content(key):
    with key.open(mode='rb') as fd:
        return fd.read()


def find_free_tcp_port():
    with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]


@pytest.fixture
def ldap_params():
    return {
        'ldap_url': 'ldap://localhost.entrouvert.org:%s' % find_free_tcp_port(),
    }


@pytest.fixture
def ldap_object(ldap_params):
    with Slapd(**ldap_params) as slapd:
        yield slapd


@pytest.fixture
def ldap_configure():
    pass


@pytest.fixture
def ldap_server(ldap_object, ldap_configure):
    return ldap_object


@pytest.fixture
def resource_class(db):
    from passerelle.apps.ldap.models import Resource

    return Resource


@pytest.fixture
def resource_params(ldap_params):
    return {
        'title': 'resource',
        'slug': 'resource',
        'description': 'resource',
        'ldap_url': ldap_params['ldap_url'],
    }


@pytest.fixture
def resource_access_rights(resource_object):
    from tests.utils import setup_access_rights

    setup_access_rights(resource_object)


@pytest.fixture
def resource_object(resource_class, resource_params):
    return resource_class.objects.create(**resource_params)


@pytest.fixture
def resource(resource_object, resource_access_rights):
    return resource_object
