# coding: utf-8


import re

from idm.core.constants.secret_key import SECRET_KEY

LOGIN_FIELDS = ('passportLogin', 'passport-login')
SECRET_DATA_PATTERN = re.compile('.*({}).*'.format('|'.join(SECRET_KEY.ALL)), re.IGNORECASE)
SECRET_DATA_PLACEHOLDER = '*************'
SECRET_DATA_IN_URL_PATTERN = re.compile(
    '(?P<field>[\?&]{0})=(?P<value>[^&]*)'.format('|'.join(SECRET_KEY.ALL)),
    re.IGNORECASE,
)


def filter_password(data):
    """Возвращает копию словаря, в которой все пароли заменены на 8 звёздочек."""

    if not isinstance(data, dict):
        data = {}

    data = {
        key: '*' * 8 if 'password' in key else value
        for key, value in data.items()
    }
    return data


def cleanup_fields_data(data):
    if data is None:
        return data
    if not isinstance(data, dict):
        return None
    cleaned = {}
    for key, value in data.items():
        if key in LOGIN_FIELDS and value is not None:
            cleaned['passport-login'] = value.replace('.', '-').lower()
        elif 'password' in key:
            continue
        else:
            cleaned[key] = value
    if not cleaned:
        cleaned = None
    return cleaned


def hide_secret_params(input_data):
    # Function with side-effect.
    # Replaces secret keys with placeholder.
    if isinstance(input_data, dict):
        for key in input_data:
            if isinstance(key, str) and SECRET_DATA_PATTERN.match(key):
                input_data[key] = SECRET_DATA_PLACEHOLDER
            else:
                hide_secret_params(input_data[key])
    elif isinstance(input_data, (tuple, list)):
        for item in input_data:
            hide_secret_params(item)


def hide_secret_params_in_url(input_url):
    return SECRET_DATA_IN_URL_PATTERN.sub('\g<field>={}'.format(SECRET_DATA_PLACEHOLDER), input_url)
