# Generated by Django 2.2.28 on 2022-06-08 13:59

from django.conf import settings
from django.db import migrations


def get_setting(idp, name, default, max_length=None):
    if name in idp:
        setting = idp[name]
    else:
        setting = getattr(settings, 'MELLON_' + name, default)

    expected_type = type(default)
    if expected_type is list:
        expected_type = (list, tuple)

    if not isinstance(setting, expected_type):
        setting = None
    if expected_type is int and setting and (setting < 0 or setting >= 2**15):
        setting = None

    if setting is None:
        setting = default

    return setting[:max_length] if max_length else setting


def create_saml_authenticator(apps, schema_editor):
    kwargs_settings = getattr(settings, 'AUTH_FRONTENDS_KWARGS', {})
    authenticator_settings = kwargs_settings.get('saml', {})
    show_condition = authenticator_settings.get('show_condition') or ''

    priority = authenticator_settings.get('priority')
    priority = priority if priority is not None else 3

    for i, idp in enumerate(getattr(settings, 'MELLON_IDENTITY_PROVIDERS', [])):
        if isinstance(show_condition, dict):
            show_condition_authenticator = show_condition.get(idp.get('SLUG', str(i))) or ''
        else:
            show_condition_authenticator = show_condition

        metadata_path = idp.get('METADATA_PATH') or ''
        if 'METADATA' in idp and idp['METADATA'].startswith('/'):
            metadata_path = idp['METADATA'] or ''
            del idp['METADATA']

        metadata_url = idp.get('METADATA_URL') or ''
        metadata = idp.get('METADATA') or ''
        has_valid_configuration = bool(metadata or metadata_path or metadata_url)

        SAMLAuthenticator = apps.get_model('authentic2_auth_saml', 'SAMLAuthenticator')
        SAMLAuthenticator.objects.create(
            slug=idp.get('SLUG') or str(i),
            order=priority,
            show_condition=show_condition_authenticator,
            enabled=bool(getattr(settings, 'A2_AUTH_SAML_ENABLE', False) and has_valid_configuration),
            metadata_url=metadata_url[:300],
            metadata_cache_time=get_setting(idp, 'METADATA_CACHE_TIME', 3600),
            metadata_http_timeout=get_setting(idp, 'METADATA_HTTP_TIMEOUT', 10),
            metadata_path=metadata_path[:300],
            metadata=metadata,
            provision=get_setting(idp, 'PROVISION', True),
            verify_ssl_certificate=get_setting(idp, 'VERIFY_SSL_CERTIFICATE', True),
            transient_federation_attribute=get_setting(idp, 'TRANSIENT_FEDERATION_ATTRIBUTE', '', 64),
            realm=get_setting(idp, 'REALM', 'saml', 32),
            username_template=get_setting(
                idp, 'USERNAME_TEMPLATE', '{attributes[name_id_content]}@{realm}', 128
            ),
            name_id_policy_format=get_setting(idp, 'NAME_ID_POLICY_FORMAT', '', 64),
            name_id_policy_allow_create=get_setting(idp, 'NAME_ID_POLICY_ALLOW_CREATE', True),
            force_authn=get_setting(idp, 'FORCE_AUTHN', False),
            add_authnrequest_next_url_extension=get_setting(
                idp, 'ADD_AUTHNREQUEST_NEXT_URL_EXTENSION', False
            ),
            group_attribute=get_setting(idp, 'GROUP_ATTRIBUTE', '', 32),
            create_group=get_setting(idp, 'CREATE_GROUP', True),
            error_url=get_setting(idp, 'ERROR_URL', '', 200),
            error_redirect_after_timeout=get_setting(idp, 'ERROR_REDIRECT_AFTER_TIMEOUT', 120),
            authn_classref=', '.join(get_setting(idp, 'AUTHN_CLASSREF', []))[:512],
            login_hints=', '.join(get_setting(idp, 'LOGIN_HINTS', []))[:512],
            lookup_by_attributes=get_setting(idp, 'LOOKUP_BY_ATTRIBUTES', []),
            a2_attribute_mapping=get_setting(idp, 'A2_ATTRIBUTE_MAPPING', []),
            attribute_mapping=get_setting(idp, 'ATTRIBUTE_MAPPING', {}),
            superuser_mapping=get_setting(idp, 'SUPERUSER_MAPPING', {}),
        )


class Migration(migrations.Migration):
    dependencies = [
        ('authentic2_auth_saml', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_saml_authenticator, reverse_code=migrations.RunPython.noop),
    ]
