from server_modules.util import *
import json
import re


blacklist = [
    'system.base_config.*',
    'base.system.*',
    'system.sso.*',
    'system.ldap.*',
    'system.schema.dsn',
    'system.imexporter_database.dsn'
]


def is_blacklisted(key):
    for regx in blacklist:
        if re.match(regx, key):
            return True
    return False


def flatten_config_variable(key, config, level=0, path=""):

    if path != "":
        path += "."
    path += key

    if not isinstance(config, dict):
        return [(path, config)]

    kv = []
    for k in config:
        if isinstance(config[k], dict):
            v = flatten_config_variable(k, config[k], level + 1, path)
            for t in v:
                kv.append(t)
        else:
            header = path
            if header != "":
                header += "."
            header += k
            kv.append((header, config[k]))

    return kv


def get_info(easydb_context, db_cursor, config, instance, loggername):
    data = []

    logger = easydb_context.get_logger(loggername)

    for top_variable in config:
        for sub_variable in config[top_variable]:

            if isinstance(config[top_variable], dict):
                kv = flatten_config_variable(
                    sub_variable, config[top_variable][sub_variable])
            else:
                kv = [(sub_variable, config[top_variable])]

            if len(kv) < 1:
                continue

            headers_values = []
            string_values = []
            object_values = []
            string_values_count = 0
            object_values_count = 0

            for k, v in sorted(kv, key=lambda x: x[0], reverse=False):
                if is_blacklisted(top_variable + "." + k):
                    logger.debug("skip blacklisted config variable %s" % (top_variable + "." + k))
                    continue
                headers_values.append(k)
                if isinstance(v, list) or isinstance(v, dict):
                    string_values.append('')
                    object_values.append(v)
                    object_values_count += 1
                else:
                    string_values.append(str(v))
                    string_values_count += 1
                    object_values.append(None)

            if len(headers_values) < 1:
                continue
            if string_values_count < 1 and object_values_count < 1:
                continue

            config_info = {
                'type': '2d-map',
                'name': top_variable + "." + sub_variable,
                'headers': {
                    'values': headers_values,
                    'name': 'name'
                },
                'data': []
            }

            if object_values_count > 0:
                config_info['data'].append({
                    'values': object_values,
                    'type': 'json',
                    'name': 'jsonvalue'
                })
            if string_values_count > 0:
                config_info['data'].append({
                    'values': string_values,
                    'type': 'string',
                    'name': 'stringvalue'
                })

            data.append(config_info)

    return sorted(data, key=lambda x: x['name'], reverse=False)
