<%
        import pandas as pd
        import numpy as np
        import math
%>

<% 
    # df[first_feat + quant_features + qual_features + ["pat_number"]]
    all_numeric = [0,1]
    if plotter.hash_vars["quantitative"]: 
        all_numeric += plotter.hash_vars["quantitative"]

    plotter.hash_vars["prio_table"] = plotter.df_to_numeric(plotter.hash_vars["prio_table"], all_numeric)
    plotter.hash_vars["prio_table_top100"] = plotter.get_top_rank(plotter.hash_vars["prio_table"], 100) 
    colnames = list(plotter.hash_vars["prio_table_top100"].columns)
%>
<% plotter.set_header() %>
${plotter.create_title("Integrated Report By Patient", id='main_title', hlevel=2, indexable=True, clickable=False)}

${plotter.create_title("Top Candidates", id='top_candidates', hlevel=2, indexable=True, clickable=False)}

${plotter.make_title("table", "top_gene_table", "Top 100 candidates associated with the phenotypes")}
<div style="overflow: hidden; display: flex; flex-direction: row; justify-content: center;">
        <%
            df = plotter.hash_vars["prio_table_top100"]
            
            first_three = list(df.columns[:3])
            
            rank_cols = [col for col in df.columns if col.startswith("rank_")]
            
            gene_cols = [col for col in df.columns if col.startswith("gene_symbol")]
            single_gene_col = [gene_cols[0]] if gene_cols else []
            
            other_prefixes = ("diseaseName", "diseaseCurie")
            info_cols = [col for col in df.columns if col.startswith(other_prefixes)]
            
            all_cols = first_three + rank_cols + single_gene_col + info_cols
            selected_cols = []
            for col in all_cols:
                if col not in selected_cols and col in df.columns:
                    selected_cols.append(col)
            
            df_filtered = df[selected_cols]
            df_filtered = df_filtered.rename(columns={single_gene_col[0]: "gene_symbol"})

            plotter.hash_vars["prio_table"].rename(columns={single_gene_col[0]: "gene_symbol"}, inplace=True)
            plotter.hash_vars["prio_table_top100"].rename(columns={single_gene_col[0]: "gene_symbol"}, inplace=True)
            
            table_top = df_filtered.values.tolist()
            table_top.insert(0, list(df_filtered.columns))
            plotter.hash_vars["table_top100"] = table_top
            
            dynamic_fields = list(range(len(selected_cols)))
        %>
        ${plotter.table(id="table_top100", header=True, text=True, title="", row_names=False, fields=dynamic_fields,
                        styled='dt', border=2, attrib={
                                'class': "table table-striped table-dark"})}
</div>


% if plotter.hash_vars["type_of_info_to_show"] == "both" or plotter.hash_vars["type_of_info_to_show"] == "technical":

${plotter.create_title("Distribution of quantitative values within patients", id='dist_pat', hlevel=2, indexable=True, clickable=False)}
<%
    col_subset = [colnames[idx] for idx in all_numeric[1:]] + ["pat_number"]
    pat2median = plotter.hash_vars["prio_table"][col_subset].groupby("pat_number").median().reset_index()
    pat2median = pd.melt(pat2median, id_vars='pat_number', var_name='quant_variable', value_name='melted_score')
    plotter.hash_vars["pat2median"] = plotter.df_to_list(pat2median)
%>
<%
    pat2median = plotter.hash_vars["prio_table_top100"][col_subset].groupby("pat_number").median().reset_index()
    pat2median = pd.melt(pat2median, id_vars='pat_number', var_name='quant_variable', value_name='melted_score')
    plotter.hash_vars["pat2median_top100"] = plotter.df_to_list(pat2median)
%>
<div style="overflow: hidden; display: flex; flex-direction: row; justify-content: center;">
		${plotter.boxplot(id = 'pat2median', row_names= False, header=True, title= "A", x_label= "Median",
 		fields=[2], height=250, width=500, smp_attr= [1], group="quant_variable", config={"groupingFactors": ["quant_variable"], "showViolinBoxplot":True,
 		 "colorBy": "quant_variable", "xAxisTextScaleFontFactor":1.3, 'smpTextScaleFontFactor':1.3})}
		${plotter.boxplot(id = 'pat2median_top100', row_names= False, header=True, title= "B", x_label= "Median",
 		fields=[2], height=250, width=500, smp_attr= [1], group="quant_variable", config={"groupingFactors": ["quant_variable"], "showViolinBoxplot":True,
 		 "colorBy": "quant_variable", "xAxisTextScaleFontFactor":1.3, 'smpTextScaleFontFactor':1.3})}
</div>
${plotter.make_title("figure", "pat2median", "Distribution of quantitative scores. A) All genes; B) Top 100 genes.")}


% if plotter.hash_vars["quantitative"]:
${plotter.create_title("Quantitative correlation", id='top_gene', hlevel=2, indexable=True, clickable=False)}
<%
        plotter.hash_vars["scores_corr"] = plotter.get_corr_table(plotter.hash_vars["prio_table"], [0,1]+plotter.hash_vars["quantitative"])
        plotter.hash_vars["scores_corr_top100"] = plotter.get_corr_table(plotter.hash_vars["prio_table_top100"], [0,1]+plotter.hash_vars["quantitative"])
%>
<div style="overflow: hidden; display: flex; flex-direction: row; justify-content: center;">
<div>
        ${ plotter.heatmap(id = 'scores_corr', title="A",header = True, row_names = True, 
                config= {"setMinX":-1,
                "setMaxX":1, 
                "xAxisTitle": "Spearman-corr", 
                "samplesClustered": False,
                "showSmpDendrogram": False}) }
        ${ plotter.heatmap(id = 'scores_corr_top100', title="B",header = True, row_names = True, 
                config= {"setMinX":-1,
                "setMaxX":1, 
                "xAxisTitle": "Spearman-corr", 
                "samplesClustered": False,
                "showSmpDendrogram": False}) }
</div>
</div>
${plotter.make_title("figure", "corr", "Spearman correlation between the quantitative features. A) All genes; B) Top 100 genes.")}
% endif

% endif

% if plotter.hash_vars["qualitative"] or plotter.hash_vars["quantitative"] and (plotter.hash_vars["type_of_info_to_show"] == "both" or plotter.hash_vars["type_of_info_to_show"] == "clinical"):

${plotter.create_title("Detailed information top candidates", id='top_gene', hlevel=2, indexable=True, clickable=False)}
% for i in range(0,min(25, len(plotter.hash_vars["prio_table_top100"]))):
    <%
        txt = f""
        if plotter.hash_vars["quantitative"]:
            plotter.hash_vars["table_candidate_quant"] = list(plotter.hash_vars["prio_table_top100"].iloc[i,plotter.hash_vars["quantitative"]].items())
            plotter.hash_vars["table_candidate_quant"].insert(0, ["Quantitative variables", "Value"])
            title_quant = plotter.make_title("table", f"table_quant_{i}", f"Quantitative variables")
            table_quant = plotter.table(id="table_candidate_quant", header=True, text=True, title="", row_names=False, fields=[0,1], styled='dt', border=2, attrib={'class': "table table-striped table-dark"})
            txt += """<div style="overflow: hidden; display: flex; flex-direction: row; justify-content: center;">""" + "\n"
            txt += title_quant + "\n"
            txt += table_quant + "\n"
            txt += "</div>" + "\n"
        
        if plotter.hash_vars["qualitative"]:
            plotter.hash_vars["table_candidate_qual"] = list(plotter.hash_vars["prio_table_top100"].iloc[i,plotter.hash_vars["qualitative"]].items())
            plotter.hash_vars["table_candidate_qual"].insert(0, ["Qualitative variables", "Value"])
            title_qual = plotter.make_title("table", f"table_qual_{i}", f"Qualitative variables")
            table_qual = plotter.table(id="table_candidate_qual", header=True, text=True, title="", row_names=False, fields=[0,1], styled='dt', border=2, attrib={'class': "table table-striped table-dark"})
            txt += """<div style="overflow: hidden; display: flex; flex-direction: row; justify-content: center;">""" + "\n"
            txt += title_qual + "\n"
            txt += table_qual + "\n"
            txt += "</div>" + "\n"
    %>
    <%
        if "gene_symbol" in plotter.hash_vars["prio_table_top100"].columns:
            title_text = f"Variant: {plotter.hash_vars['prio_table_top100'].iloc[i,2]} ; Gene: {plotter.hash_vars['prio_table_top100']['gene_symbol'].iloc[i]}"
        else:
            title_text = f"Variant: {plotter.hash_vars['prio_table_top100'].iloc[i,2]}"
    %>
    ${plotter.create_title(title_text, id=f"tables_quant_qual{i}i", indexable=False, clickable=True, hlevel=2, t_id=f"tables_quant_qual{i}")}
    ${plotter.create_collapsable_container(f"tables_quant_qual{i}", txt)}
% endfor
% endif


