# authentic2 - versatile identity manager
# Copyright (C) 2010-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 authentic2.constants import SERVICE_FIELD_NAME


def service_ref(service):
    if service.ou:
        return '%s %s' % (service.ou.slug, service.slug)
    else:
        return service.slug


def get_service_from_ref(ref):
    from authentic2.models import Service

    splitted = ref.split(' ')

    try:
        ou_slug, service_slug = splitted
    except ValueError:
        pass
    else:
        return Service.objects.filter(ou__slug=ou_slug, slug=service_slug).first()

    try:
        (service_slug,) = splitted
    except ValueError:
        return None

    service = Service.objects.filter(ou__isnull=True, slug=service_slug).first()
    if service:
        return service
    try:
        return Service.objects.get(slug=service_slug)
    except (Service.DoesNotExist, Service.MultipleObjectsReturned):
        return None


def get_service_from_request(request):
    service_ref = request.GET.get(SERVICE_FIELD_NAME)
    if service_ref and '\x00' not in service_ref:
        return get_service_from_ref(service_ref)
    return None


def get_service_from_session(request):
    session = getattr(request, 'session', None)
    if session and 'service_pk' in session:
        from authentic2.models import Service

        return Service.objects.get(pk=session['service_pk'])
    return None


def get_service_from_token(params):
    ref = params.get(SERVICE_FIELD_NAME)
    if not ref:
        return None
    return get_service_from_ref(ref)


def set_service_ref(params, service):
    params[SERVICE_FIELD_NAME] = service_ref(service)
