import statistics
from db06 import DBAccess

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

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

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

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

  #埋め込み：集計テーブル
  total_list_content = ''
  for res in sorted(DBAccess.get_record_totalization(), key=lambda res: res[1], reverse=True):
    # 色変更用変数の設定
    trBgColor = POSI_BG_COLOR if res[1] >= boundaryValue else NEGA_BG_COLOR
    trColor   = POSI_COLOR    if res[1] >= boundaryValue 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(trBgColor ,trColor, res[0], res[1], res[2])

    #埋め込み：集計グラフ
    chart_content = ''
    chart_content += '''
        <br>
        <div>
            <canvas id="myChart" width="100" height="100"></canvas>
        <div>
        <script>

            // 値を設定
            var datasets = [
                {
                    data: [
    '''
    #配列より評価値の取得
    for assessment in assessment_list:
       chart_content +=  str(assessment) + ','
    
    chart_content += '''      
                    ],
                    backgroundColor: [] // グラフ色用配列
                },
            ]

            // 各棒グラフの値が正か負かによって色分け
            for (var i = 0; i < datasets[0].data.length; i++) {
                if (datasets[0].data[i] > ''' + str(boundaryValue)  + '''){
                    datasets[0].backgroundColor[i] = " ''' + POSI_BG_COLOR  + ''' " // ポジティブ
                } else {
                    datasets[0].backgroundColor[i] = " ''' + NEGA_BG_COLOR  + ''' " // ネガティブ
                }
            }  

            //円グラフ（ドーナッツ型）
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
                //グラフの種類　pie or doughnut
                type: 'doughnut',
                data: {
                    //データ項目のラベル
                    labels: [
    '''
    #配列より項目名の取得
    for item in item_list:
        chart_content +=  '"' + str(item) + '",'
    
    chart_content += '''
                    ],
                    datasets: datasets
                },
                    options: {
                        responsive: true , hover: {mode: null}
                    },
                }
            );
        </script>
    '''

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

  #<body>内容を出力
  html_Text = file.format( 
    embed_record_list = total_list_content ,
    embed_chart_script = chart_content
  )

  return html_Text