import click


def networkx_to_dict(ngraph, verbose=True):
    """Turn the networkx data into a dict structure that can be consumed by the dataviz

    Note
    --------
    The network data is extracted as follows

    > xx = G.nodes(data=True)
    > for x in xx:
        print(x[1])
    ('respiratory tract infections', {'frequency': 145, 'freq_normalized': 92.77215189873418, 'score_avg': 0.63237, 'score_bucket': 2, 'size': 10})
    ('acute lung injury', {'frequency': 9, 'freq_normalized': 6.69620253164557, 'score_avg': 0.62226, 'score_bucket': 2, 'size': 10})
    .....


    > yy = G.edges(data=True)
    > for y in yy:
        print(y)
    ('respiratory tract infections', 'MERS-CoV infection', {'weight': 2})
    ('respiratory tract infections', 'lower respiratory tract infections', {'weight': 53})
    ....

    Parameters
    ----------
    ngraph : networkx.Graph
        DSL data turned into a graph

    Returns
    ----------
    tuple 
        A tuple containing two dictionaries ready to be turned into visjs JSON data sources. 
        For example

            nodes =  [
                {'id': 1, 'label': 'Knowledge Graphs'},
                {'id': 2, 'label': 'RDF'},
                {'id': "3 3", 'label': 'Linked Data'}
                ]

            edges = [
                {'from': 1, 'to': "3 3"},
                {'from': 1, 'to': 2},
                {'from': "3 3", 'to': 2}
                ]
    """


    if not ngraph:
        return [], []  # nodes, edges

    NODES = []
    if verbose: click.secho(f"Creating Dict for visjs dataviz.. ", fg="green")
    if verbose: click.secho(f"..nodes.. ", dim=True)

    def safe_id(_id):
        return _id.replace(" ", "_").strip()


    # px.colors.diverging.Temps
    TEST_COLORS = ['rgb(0, 147, 146)',
                    'rgb(57, 177, 133)',
                    'rgb(156, 203, 134)',
                    'rgb(233, 226, 156)',
                    'rgb(238, 180, 121)',
                    'rgb(232, 132, 113)',
                    'rgb(207, 89, 126)']


    for x in ngraph.nodes(data=True):
        # id and label, the same; freqn = size [TBC]
        _id, label, freq, freqn = safe_id(x[0]), x[0].capitalize(), x[1]['frequency'], x[1]['freq_normalized']
        score_avg, score_bucket = x[1]['score_avg'], x[1]['score_bucket']

        temp = {'id': _id, 'label': label, 'group': 1}
        temp['value'] = int(freqn) 
        temp['freq'] = int(freq) 
        temp.update(x[1]) # add all other features too
        # TEST COLORS hardcoded
        temp['color'] = TEST_COLORS[3*score_bucket]
        # HTML titles
        temp['title'] = f"<h4>Concept: {label}</h4><hr>Frequency Norm: {freqn}<br>Frequency: {freq}<br>Score avg: {score_avg}<br>Score bucket: {score_bucket}"
        # temp['title'] = json.dumps(x[1], sort_keys=True, indent=4)  # title = original JSON contents
        NODES.append(temp)

    EDGES = []
    if verbose: click.secho(f"..edges.. ", dim=True)

    for x in ngraph.edges(data=True):
        # id and label, the same
        temp = {'from': safe_id(x[0]), 'to': safe_id(x[1])}
        temp['value'] = int(x[2]['weight']) 
        temp.update(x[2]) # add all other features too
        temp['title'] = f"Strength: {x[2]['weight']}"

        EDGES.append(temp)

    if verbose: click.secho(f"Done", dim=True)
    return NODES, EDGES