import statistics
from db06 import DBAccess

#分析機能画面作成
def makepage_analyze():

  #色設定
  POSI_BG_COLOR = '#fff2f2'
  POSI_COLOR    = '#e65050'
  NEGA_BG_COLOR = '#fafafa'
  NEGA_COLOR    = '#3d3838'

  #評価の中央値
  boundary = statistics.median([1,2,3,4,5,6])

  #グラフ表示用
  item_list = []
  assessment_list = []

  #埋め込み：集計テーブル
  total_list_content = ''
  for res in DBAccess.get_record_totalization():
    # 色変更用変数の設定
    tr_bg_color = POSI_BG_COLOR if res[1] >= boundary else NEGA_BG_COLOR
    tr_color   = POSI_COLOR    if res[1] >= boundary else NEGA_COLOR

    # グラフ表示用に配列に格納しておく
    item_list.append(res[0])
    assessment_list.append(res[1])

    total_list_content += '''
      <tr style="background-color:{0};color:{1};">
          <td>{2}</td>
          <td class="analysis-r">{3}</td>
          <td class="analysis-r">{4}</td>
      </tr>
    '''
    total_list_content = total_list_content.format(tr_bg_color ,tr_color, res[0], res[1], res[2])

  #埋め込み：集計グラフ
  chart_datasets = ''
  chart_config = ''
  chart_doughnut = ''

  #埋め込み：datasets-data
  chart_datasets = 'var datasets = [ { data: ['
  for assessment in assessment_list:
    chart_datasets += str(assessment) + ','
  chart_datasets += '], backgroundColor: [] } ]'

  #埋め込み：datasets-backgroundColor
  chart_datasets += '''
      for (var i = 0; i < datasets[0].data.length; i++) {
          if (datasets[0].data[i] > ''' + str(boundary)  + '''){
              datasets[0].backgroundColor[i] = " ''' + POSI_COLOR  + ''' " // ポジティブ
          } else {
              datasets[0].backgroundColor[i] = " ''' + NEGA_COLOR  + ''' " // ネガティブ
          }
      }
  '''

  #埋め込み：config
  chart_config += 'var config = { type: "doughnut" , data: { labels: [ '
  for item in item_list:
    chart_config += '"' + str(item) + '" ,'
  chart_config += '] , datasets: datasets } } '

  #埋め込み：円グラフ（ドーナッツ型）
  chart_doughnut += 'var ctx = document.getElementById("myChart");'
  chart_doughnut += 'var myChart = new Chart( ctx, config );'

  #HTMLファイルを開く
  with open('sub_analyze.html', mode='r', encoding='utf-8') as f:
    file = f.read()

  #<body>内容を出力
  html_Text = file.format( 
    embed_total_list = total_list_content,
    embed_chart_script_01 = chart_datasets,
    embed_chart_script_02 = chart_config,
    embed_chart_script_03 = chart_doughnut
  )

  return html_Text

#埋め込み：datasets
#例：[ { data: [値,値,値,], backgroundColor: [] } ]

#埋め込み：backgroundColor
#例： datasets[0].backgroundColor[i] = " #e65050 "

#埋め込み：円グラフ（ドーナッツ型）
#例：
# document.getElementById("myChart");
# var myChart = new Chart(ctx,
#   {type: "doughnut", 
#    data: {labels: ["XX並" ,"XX並" ,] , datasets: datasets},
#    options: {responsive: true , hover: {mode: null} }
#   }
# );