<%
idx2condition = {idx: "-".join(condition.split('-')[:-1]) 
  for idx, condition in enumerate(plotter.hash_vars['external_meta'][0][1:])}

def add_div(html_code):
  return f'<div style="display: inline-block; margin: 20px auto;">{html_code}</div>\n'

def make_title(type, id, sentence):
        if type == "table":
                key = f"tab:{id}"
                html_title = f"<p style='text-align:center;'> <b> {type.capitalize()} {plotter.add_table(key)} </b> {sentence} </p>"
        elif type == "figure":
                key = id
                html_title = f"<p style='text-align:center;'> <b> {type.capitalize()} {plotter.add_figure(key)} </b> {sentence} </p>"
        return html_title
%>

<div style="text-align: center; width: 100%;">

  <div style="display: inline-block; margin: 20px auto;"> 
  ${plotter.scatter2D(id="reduced_coords", fields=[2,3], header=True,
    row_names=False, smp_attr=[0,1,4],
    height='400px', width='400px',
    x_label='UMAP-1', y_label='UMAP-2', title='UMAP projection of samples colored by clusters',
    config={
     "colorBy": "cluster_id", 
     "showLegend": True,
     "legendTitle": "Cluster ID",
     "pointSize": 100,
     "titleFontStyle":"italic",
     "colorScheme": "Accent",
     "titleScaleFontFactor":0.7})}
  </div>
  ${make_title("figure", "scatter2d_reduced", "UMAP projection of samples colored by clusters")}

  <div style="display: inline-block; margin: 20px auto;">
  ${plotter.scatter2D(id="reduced_coords", fields=[2,3], header=True,
    row_names=False, smp_attr=[0,1,4],
    height='400px', width='400px',
    x_label='UMAP-1', y_label='UMAP-2', title='UMAP projection of samples colored by clusters',
    config={
     "colorBy": "is_stratified", 
     "showLegend": True,
     "legendTitle": "Is stratified?",
     "pointSize": 100,
     "titleFontStyle":"italic",
     "colorScheme": "TableauLight",
     "colorKey":{"is_stratified":{"NA":"#989898","false":"#c60202", "true":"#00b709"}},
     "titleScaleFontFactor":0.7})}
  </div>
  ${make_title("figure", "scatter2d_stratified", "UMAP projection of samples colored by stratification status")}

  ${make_title("table", "metrics", "Cluster analysis metrics")}
  <div style="display: inline-block; margin: 20px auto;">
  ${plotter.table(id="metrics", header=True, row_names=False, responsive=True, height='400px', width='100%',
    x_label='Metric', y_label='Value', title='Cluster analysis metrics',
    config={"titleFontStyle":"italic", "titleScaleFontFactor":0.7})}
  </div>

  % for cluster_id in plotter.hash_vars['clusters_id']:

  	<%
      cluster_data = [row for row in plotter.hash_vars['reduced_coords'] if row[1] == cluster_id]
      plotter.hash_vars['cluster_data'] = cluster_data
      subset_points = sorted(list(set([row[0] for row in cluster_data[:]])))
      plotter.hash_vars['subset_external_meta'] = [row for row in plotter.hash_vars['external_meta'] if row[0] in subset_points]
      plotter.hash_vars['subset_external_meta'].insert(0, plotter.hash_vars['external_meta'][0])
      print(plotter.hash_vars['subset_external_meta'])
  	%>

  	<% 
      collapsable_plot = add_div(plotter.scatter2D(id="cluster_data", fields=[2,3], header=True,
  	  row_names=False, smp_attr=[0,1,4],
  	  height='400px', width='400px',
  	  x_label='Original Dim 1', y_label='Original Dim 2', title=f'Original projection of samples in cluster {cluster_id}',
  	  config={
  	   "colorBy": "is_stratified", 
  	   "showLegend": True,
  	   "legendTitle": "Is stratified?",
  	   "pointSize": 100,
  	   "titleFontStyle":"italic",
  	   "titleScaleFontFactor":0.7}))

      collapsable_plot += add_div(plotter.line(id='subset_external_meta', header=True, row_names=True, x_label="counts", title="",
      transpose=False, config={"graphOrientation": "vertical","lineThickness": 3}))

      table_data = [["sample", "condition", "value"]]
      for row in plotter.hash_vars['subset_external_meta'][1:]:
        sample_id = row[0]
        for idx, value in enumerate(row[1:]):
          condition = idx2condition[idx]
          table_data.append([sample_id, condition, value])
      plotter.hash_vars['subset_external_meta_long'] = table_data

      collapsable_plot += add_div(plotter.boxplot(id='subset_external_meta_long', format="long",
       header=True,
       row_names=False, fields=[2], x_label="counts", title="",
       smp_attr=[0,1], group=["sample", "condition"],
       config = { 
        'groupingFactors': ["sample", "condition"],
        'colorBy': "condition",
        'segregateSamplesBy': [],
        'showBoxplotIfViolin': True,
        'showViolinBoxplot': True}
      ))
    %>
    ${plotter.create_title(f"External metadata distribution in cluster {cluster_id}",
        id=f'click{cluster_id}',
        hlevel=1,
        indexable=True,
        clickable=True,
        t_id=f"clickme_{cluster_id}",
        clickable_text = '(Click me)')}
    ${plotter.create_collapsable_container(f"clickme_{cluster_id}", collapsable_plot)}
  % endfor
</div>