# passerelle.contrib.agoraplus
# Copyright (C) 2015  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 json
import requests
import logging

from django.conf import settings


logger = logging.getLogger('passerelle.contrib.agoraplus')

def get_authentic_url():
    if hasattr(settings, 'KNOWN_SERVICES'):
        return settings.KNOWN_SERVICES.get('authentic').items()[0][1]['url']
    return None

def provision_roles(uuid, method='POST'):
    roles_uuids = getattr(settings, 'PASSERELLE_APP_AGORAPLUS_ROLES_UUIDS', None)
    if not roles_uuids:
        return
    authentic_url = get_authentic_url()
    credentials = getattr(settings, 'AUTHENTIC_AUTH_TUPLE', None)
    if not authentic_url or not credentials:
        return
    # if credentials is it settings.json, it's a list, cast it:
    credentials = tuple(credentials)
    for role_uuid in roles_uuids:
        logger.info('%s role %s to user NameID:%s', method, role_uuid, uuid)
        requests.request(method, authentic_url + 'api/roles/%s/members/%s/' % (role_uuid, uuid),
                         headers={'Content-type': 'application/json'}, auth=credentials)

def patch_authentic_user(uuid, user):
    authentic_url = get_authentic_url()
    credentials = getattr(settings, 'AUTHENTIC_AUTH_TUPLE', None)
    if not authentic_url or not credentials:
        return
    # if credentials is it settings.json, it's a list, cast it:
    credentials = tuple(credentials)
    data = json.dumps(user)
    logger.debug('patch Authentic user NameID:%s with data:%s', uuid, data)
    authentic_responses = requests.patch(
        authentic_url + 'api/users/' + uuid + '/',
        data=data,
        headers={'Content-type': 'application/json'},
        auth=credentials)
    if authentic_responses.status_code != 200:
        logger.warning('patch Authentic user NameID:%r returns status_code %r', uuid,
                       authentic_responses.status_code)

def provision_attributes(family, login, name_id):
    # get adult from the family
    for adult in family.get('adults', []):
        if adult['login'] == login:
            break
    else:
        return
    # build Authentic api user
    user = {}
    if adult.get('address'):
        user['address'] = adult['address']['text']
        user['zipcode'] = adult['address']['post_code']
        user['city'] = adult['address']['city']['text']
        user['country'] = adult['address'].get('country', '')
    if adult.get('cellphone'):
        user['mobile'] = adult['cellphone']
    if adult.get('phone'):
        user['phone'] = adult['phone']
    # send it to Authentic IdP
    if user:
        patch_authentic_user(uuid=name_id, user=user)
