{% extends 'space_base.html' %}
{% load staticfiles %}

{% block main %}

  <div class="row">
    {% if cluster %}
    <div class="col-md-6">
      <div class="card">
        <div class="card-header" style="font-weight: bold;">{{ cluster.name }}</div>
        <div class="card-body">
            <table class="table">
              <tbody>
                {% for k,v in cluster.items%}
                <tr>
                  <th style="color: #16588c;">{{k}}</th>
                  <td>{{v}}</td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
        </div>

        <!-- <div class="panel-footer"><a href="" class="btn btn-info">OPEN</a></div> -->

      </div>
            
      </div>

    
    <div class="col-md-6" id="metrics_parent">
      <h4 class="page-header" style="margin-top: 20px;">
        Cluster Overview
      </h4>
      <div id="metrics_div" class="row" style="margin-top: 20px;"></div> 
    </div>     

    <div class="col-md-12" id="dataset_parent">
      <h4 class="page-header"  style="margin-top: 20px;">
        Dataset Overview
      </h4>
      <div class="row">
      <div id="dataset_1" class="col-md-6" style="height: 300px;"></div>
      <div id="dataset_2" class="col-md-6" style="height: 300px;"></div>
      </div>
    </div>

    <div class="col-md-12" id="instance_parent">    
      <h4 class="page-header"  style="margin-top: 20px;">
        Instance Overview
      </h4>
      <div id="instance_1" style="height: 300px;max-width: 600px;"></div>
    </div>

    <div class="col-md-12" id="pipeline_parent">
      <h4 class="page-header"  style="margin-top: 20px;">
        Pipeline Overview
      </h4>
      <div id="pipeline_div">        
      </div>
    </div>
    
    <div class="col-md-12" id="notebook_parent">
      <h4 class="page-header"  style="margin-top: 20px;">
        Notebook Overview
      </h4>
      <div id="notebook_div"></div>
    </div>
    <script type="text/javascript" src="{% static 'scispace/js/echarts.min.js' %}"></script>
    <script type="text/javascript">
      var data_metrics_url = "{%url 'scispace_get_data_metrics_ajax' cluster.id %}";
      var hosts_metrics_url = "{%url 'scispace_get_hosts_metrics_ajax' cluster.id %}";
      var piflow_data_url = "{{pipeline_api_url}}";
      var zeppelin_data_url = "{{notebook_api_url}}";
      var hosts_metrics = { {%for h in hosts%}
                    "{{h.hostname}}":{"disk_free":200,"disk_total":500,"mem_total":8174516.0,"mem_free":4820708.0},
                    {%endfor%} };

      var hosts_options = {};
      var hosts_charts = {};
      function get_hosts_option(hostname,disk_free,disk_total,mem_total,mem_free) {
        return {
                  title: {
                          text: hostname,
                          //subtext: '虚构数据',
                          left: 'center'
                      },
                  color: ['#59b3d5', '#cc2f36'],
                  tooltip: {
                          trigger: 'item',
                          formatter: "{a} <br/>{b} : {c}"
                      },
                  legend: {
                          orient: 'vertical',
                          left: 'left',
                          data: ['DiskFree','DiskUsed']
                      },
                  series: [{
                            name: 'Disk',
                            type: 'pie',
                            radius: '60%',
                            center: ['25%', '50%'],
                            data: [{
                                  value: disk_free,
                                  name: 'DiskFree'
                                }, 
                                {
                                  value: (disk_total - disk_free).toFixed(2),
                                  name: 'DiskUsed'
                              }],
                            itemStyle: {
                                  emphasis: {
                                      show: true,
                                      textStyle: {
                                          fontSize: '20',
                                          fontWeight: 'bold'
                                      }
                                  },
                            normal: {
                                      position: 'center',
                                      label: {
                                          formatter: function(a, b, c, d) {
                                            return a.data.value + 'GB ';
                                          },
                                          position: 'inside',
                                          // textStyle: {
                                          //     baseline: 'top',
                                          //     fontSize: '12',
                                          //     fontWeight: 'bold',
                                          // }
                                      }
                                  },
                              }
                          },
                          {
                              name: 'Memory',
                              type: 'gauge',
                              radius: '70%',
                              center: ['65%', '50%'],
                              min: 0,
                              max: Math.ceil(mem_total/(1024*1024)),
                              axisLine: {            // 坐标轴线
                                  lineStyle: {       // 属性lineStyle控制线条样式
                                      width: 10
                                  }
                              },
                              axisTick: {            // 坐标轴小标记
                                  length: 15,        // 属性length控制线长
                                  lineStyle: {       // 属性lineStyle控制线条样式
                                      color: 'auto'
                                  }
                              },
                              splitLine: {           // 分隔线
                                  length: 20,         // 属性length控制线长
                                  lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                                      color: 'auto'
                                  }
                              },
                              detail: {formatter:'{value}'+"GB"},
                              data: [{
                                  value: ((mem_total - mem_free)/(1024*1024)).toFixed(2), 
                                  name: 'Memory(GB)'
                                  }]
                          }
                      ]
                  };
      }

      jQuery(function($) {

        // init hosts metrics
        var content_eles = "";
        var metics_div = document.getElementById("metrics_div");
        var i = 0;
        for(var key in hosts_metrics){
          content_eles += ('<div id="host' + i + '" class="col-md-12" style="height:300px;"></div>');
          i += 1;          
        }
        metrics_div.innerHTML = (content_eles);
        i = 0;
        for(var key in hosts_metrics){
          var disk_div_element = document.getElementById('host' + i);
          i += 1;

          var diskChart = echarts.init(disk_div_element);
          var disk_free = hosts_metrics[key]["disk_free"];
          var disk_total = hosts_metrics[key]["disk_total"];
          var mem_free = hosts_metrics[key]["mem_free"];
          var mem_total = hosts_metrics[key]["mem_total"];
          var option = get_hosts_option(key,disk_free,disk_total,mem_total,mem_free);
          diskChart.setOption(option);
          hosts_options[key] = option;
          hosts_charts[key] = diskChart;
        }

        // init data metrics
        $.get( data_metrics_url, function(data) {
          data = data.metrics;
          var data_sets_type_cnt = data.dataset.type_cnt;
          if (data_sets_type_cnt && data_sets_type_cnt.length > 0) {
              var dataset_div_element_1 = document.getElementById('dataset_1');
              var dataset_chart_1_option_data_x = [];
              var dataset_chart_1_option_data_y = [];
              for (var i = 0; i < data_sets_type_cnt.length; i++) {
                  dataset_chart_1_option_data_x.push(data_sets_type_cnt[i].type);
                  dataset_chart_1_option_data_y.push(data_sets_type_cnt[i].cnt);
              }
              var dataset_chart_1 = echarts.init(dataset_div_element_1);
              var dataset_chart_1_option = {
                  title: {
                      text: '',
                      subtext: '',
                      left: 'center'
                  },
                  color: ['#59b3d5'],
                  tooltip: {
                      trigger: 'axis',
                      axisPointer: { // 坐标轴指示器，坐标轴触发有效
                          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                      }
                  },
                  grid: {
                      left: '10',
                      right: '80',
                      bottom: '10',
                      containLabel: true
                  },
                  xAxis: [{
                      type: 'category',
                      name: 'DataType',
                      //data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                      data: dataset_chart_1_option_data_x,
                      axisTick: {
                          alignWithLabel: true
                      }
                  }],
                  yAxis: [{
                      type: 'value',
                      name: 'Count',
                      axisLabel:{formatter:'{value}'}
                  }],
                  series: [{
                      name: '大小',
                      type: 'bar',
                      barWidth: '60%',
                      //data: [10, 51, 100, 334, 390, 330, 110]
                      data: dataset_chart_1_option_data_y
                  }]
              };
              dataset_chart_1.setOption(dataset_chart_1_option);
          }

          var data_sets_type_size = data.dataset.type_size;
          if (data_sets_type_size && data_sets_type_size.length > 0) {
              var dataset_div_element_2 = document.getElementById('dataset_2');
              var dataset_chart_2_option_data_x = [];
              var dataset_chart_2_option_data_y = [];
              for (var i = 0; i < data_sets_type_size.length; i++) {
                  dataset_chart_2_option_data_x.push(data_sets_type_size[i].type);
                  dataset_chart_2_option_data_y.push(Math.round(data_sets_type_size[i].size/1024)); //convert MB
              }
              var dataset_chart_2 = echarts.init(dataset_div_element_2);
              var dataset_chart_2_option = {
                  title: {
                      text: '',
                      subtext: '',
                      left: 'center'
                  },
                  color: ['#93c4af'],
                  tooltip: {
                      trigger: 'axis',
                      axisPointer: { // 坐标轴指示器，坐标轴触发有效
                          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                      }
                  },
                  grid: {
                      left: '10',
                      right: '80',
                      bottom: '10',
                      containLabel: true
                  },
                  xAxis: [{
                      type: 'category',
                      name: 'DataType',
                      //data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                      data: dataset_chart_2_option_data_x,
                      axisTick: {
                          alignWithLabel: true
                      }
                  }],
                  yAxis: [{
                      type: 'value',
                      name: 'Size/MB',
                      axisLabel:{formatter:'{value}'}
                  }],
                  series: [{
                      name: 'Size',
                      type: 'bar',
                      barWidth: '60%',
                      //data: [10, 52, 200, 334, 390, 330, 220]
                      data: dataset_chart_2_option_data_y,
                      // normal: {
                      //     position: 'center',
                      //     label: {
                      //         formatter: function(a, b, c, d) {
                      //             return a.data.value + 'MB ';
                      //         }
                      //     }
                      // },
                  }]
              };
              dataset_chart_2.setOption(dataset_chart_2_option);
          }

          if(!data_sets_type_size && !data_sets_type_cnt){
            // hidden parent element
            var pr = document.getElementById("dataset_parent");
            pr.style.display="none";
          }

          var data_instance_type_cnt = data.instance.type_cnt;
          if (data_instance_type_cnt && data_instance_type_cnt.length > 0) {
              var instance_div_element_1 = document.getElementById('instance_1');
              var instance_chart_1_option_data_x = [];
              var instance_chart_1_option_data_y = [];
              for (var i = 0; i < data_instance_type_cnt.length; i++) {
                  instance_chart_1_option_data_x.push(data_instance_type_cnt[i].dataset__type);
                  instance_chart_1_option_data_y.push(data_instance_type_cnt[i].cnt);
              }
              var instance_chart_1 = echarts.init(instance_div_element_1);
              var instance_chart_1_option = {
                  title: {
                      text: '',
                      subtext: '',
                      left: 'center'
                  },
                  color: ['#eacc6c'],
                  tooltip: {
                      trigger: 'axis',
                      axisPointer: { // 坐标轴指示器，坐标轴触发有效
                          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                      }
                  },
                  grid: {
                      left: '10',
                      right: '80',
                      bottom: '10',
                      containLabel: true
                  },
                  xAxis: [{
                      type: 'category',
                      name: 'DataType',
                      data: instance_chart_1_option_data_x,
                      axisTick: {
                          alignWithLabel: true
                      }
                  }],
                  yAxis: [{
                      type: 'value',
                      name: 'Count',
                  }],
                  series: [{
                      name: 'Count',
                      type: 'bar',
                      barWidth: '50%',
                      //data: [10, 52, 200, 334, 390, 330, 220]
                      data: instance_chart_1_option_data_y
                  }]
              };
              instance_chart_1.setOption(instance_chart_1_option);
          }
          else{
            // hidden parent element
            var pr = document.getElementById("instance_parent");
            pr.style.display="none";
          }
        });


        $.get( piflow_data_url, function(result) {
          if (result) {
              var rtnMap = JSON.parse(result);
              if (1 === rtnMap.code) {
                  var result_data = rtnMap.data;
                  if (result_data && result_data.length > 0) {
                      var pipeline_div = document.getElementById("pipeline_div");
                      var content_eles = "<ol>";                      
                      for (var i = 0; i < result_data.length; i++) {
                          content_eles += ('<li>' + result_data[i].name + '</li>')
                      }
                      content_eles += "</ol>";
                      pipeline_div.innerHTML = content_eles;
                  }
              }
          }
        });

        $.get(zeppelin_data_url, function(result) {
          if (result) {
              if ("OK" === result.status) {
                var result_body = result.body;
                if (result_body && result_body.length > 0) {
                    var notebook_div = document.getElementById("notebook_div");
                    var content_eles = "<ol>"; 
                    for (var i = 0; i < result_body.length; i++) {
                        content_eles += ('<li>' + result_body[i].name + '</li>')
                    }
                    content_eles += "</ol>";
                    notebook_div.innerHTML = content_eles;
                }
              }
          }
        });

        // update hosts metrics
        update_hosts_metrics();
      });

    function update_hosts_metrics(){
      setInterval("set_hosts_metrics()", 60000);
      set_hosts_metrics();
      }

    function set_hosts_metrics() {
      $.get( hosts_metrics_url, function(data) {
          var metrics_array = data.metrics;
          if (metrics_array && metrics_array.length > 0) {
              for (var i = 0; i < metrics_array.length; i++) {
                  var metrics_array_i = metrics_array[i];
                  for(var k in metrics_array_i){
                    metrics = metrics_array_i[k]["metrics"];
                    if(hosts_charts.hasOwnProperty(k)){
                      disk_free = metrics["disk"]["disk_free"];
                      disk_total = metrics["disk"]["disk_total"];
                      mem_free = metrics["memory"]["mem_free"];
                      mem_total = metrics["memory"]["mem_total"];
                      var option = get_hosts_option(k,disk_free,disk_total,mem_total,mem_free);
                      hosts_charts[k].setOption(option,true);
                    }
                  }                  
              }
          }
          else{
            // hidden parent element
            var pr = document.getElementById("metrics_parent");
            pr.style.display="none";
          }
      });
    }
    
    </script>

    {% endif %}
  </div>

{% endblock %}
