import json
import itertools
import numpy as np
import pandas as pd
import re

def jsonify_dataframe_column(dataframe, column):
    jsonified_column = [json.dumps(value) for value in dataframe[column]]
    dataframe[column] = jsonified_column
    return dataframe

def melt_series(s):
    lengths = s.str.len().values
    flat = [i for i in itertools.chain.from_iterable(s.values.tolist())]
    idx = np.repeat(s.index.values, lengths)
    return pd.Series(flat, idx, name=s.name)

def melt_dataframe(dataframe, melting_column, renaming_mapping):
    return melt_series(dataframe[melting_column]).to_frame().rename(renaming_mapping, axis=1).join(dataframe)

def add_sort_table_to_html_header(table_html, column_name, column_index):
    """
    Works with the html code ouptputed from a 'pd.to_html()'
    """
    table_html = re.sub('<th>{}'.format(column_name),
                        '<th onclick="sortTable({})">{}'.format(column_index, column_name),
                        table_html)
    return table_html