import sys
import os
root_dir = os.path.abspath(os.curdir)
sys.path.append(root_dir)

import h5py
import yaml

import numpy as np
import pandas as pd

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
#import plotly.io as pio
from src.hdf5_ops import get_parent_child_relationships

 

def display_group_hierarchy_on_a_treemap(filename: str):

    """
    filename (str): hdf5 file's filename"""

    with h5py.File(filename,'r') as file:
        nodes, parents, values = get_parent_child_relationships(file)

        metadata_list = []
        metadata_dict={}
        for key in file.attrs.keys():            
            #if 'metadata' in key:
            if isinstance(file.attrs[key], str):  # Check if the attribute is a string
                metadata_key = key[key.find('_') + 1:]
                metadata_value = file.attrs[key]
                metadata_dict[metadata_key] = metadata_value
                metadata_list.append(f'{metadata_key}: {metadata_value}')
            
            #metadata_dict[key[key.find('_')+1::]]= file.attrs[key]
            #metadata_list.append(key[key.find('_')+1::]+':'+file.attrs[key])

        metadata = '<br>'.join(['<br>'] + metadata_list)

    customdata_series = pd.Series(nodes)
    customdata_series[0] = metadata

    fig = make_subplots(1, 1, specs=[[{"type": "domain"}]],)
    fig.add_trace(go.Treemap(
        labels=nodes, #formating_df['formated_names'][nodes],
        parents=parents,#formating_df['formated_names'][parents],
        values=values,
        branchvalues='remainder',
        customdata= customdata_series,
        #marker=dict(
        #    colors=df_all_trees['color'],
        #    colorscale='RdBu',
        #    cmid=average_score),
        #hovertemplate='<b>%{label} </b> <br> Number of files: %{value}<br> Success rate: %{color:.2f}',
        hovertemplate='<b>%{label} </b> <br> Count: %{value} <br> Path: %{customdata}',
        name='',
        root_color="lightgrey"
        ))
    fig.update_layout(width = 800, height= 600, margin = dict(t=50, l=25, r=25, b=25))
    fig.show()
    file_name, file_ext = os.path.splitext(filename)
    fig.write_html(file_name + ".html")
   
    #pio.write_image(fig,file_name + ".png",width=800,height=600,format='png')

#
