[% USE date %]
[% histou_frame_url = histou_url.replace('/dashboard/', '/dashboard-solo/').replace('/d/', '/d-solo/') %]
<script>
  var histou_url        = "[% histou_url %]";
  var histou_frame_url  = "[% histou_frame_url %]";
  var histou_source     = "[% histou_source %]";

  /* try to fetch sources */
  var source_url = histou_url.replace(/\/grafana\/dashboard\/script\/histou\.js\?/, '/histou/index.php?');
  if(source_url.match("/histou/index.php")) {
    jQuery.ajax({
      url: source_url,
      type: 'POST',
      xhrFields: {
        withCredentials: true
      },
      success: function(data) {
        data = data.replace(/^[\s\S]*<br>\{/, '{');
        data = data.replace(/<br><\/pre>$/, '');
        data = data.replace(/\n/g, '');
        eval('data = '+data+";");
        var has_graphs = 0;
        jQuery('#histou_source_select').find('option').remove();
        jQuery(data.rows).each(function(i, row) {
            jQuery(row.panels).each(function(j, panel) {
              var title = replaceHistouTitle(panel.title, '[% escape_js(hst) %]', '[% escape_js(svc) %]');
              jQuery('#histou_source_select').append('<option value="'+panel.id+'"'+((panel.id==histou_source || title == histou_source) ? ' selected' : '')+'>'+title+'<\/option>');
              has_graphs++;
            });
        });
        if(has_graphs > 1) {
          jQuery('#histou_source_select').show();
        } else {
          jQuery('#histou_source_select').hide();
        }
      },
      error: ajax_xhr_error_logonly
    });
  } else {
    // extract panels from plain grafana dashboard
    var matches = source_url.match(/(?:d|d-solo|dashboard)\/([^\/]+)\//);
    if(matches && matches[1]) {
      var dashboard_id = matches[1];
      var api_url = source_url.replace(/\/grafana\/.*$/, '/grafana/api/dashboards/uid/'+dashboard_id)
      jQuery.ajax({
        url: api_url,
        type: 'GET',
        xhrFields: {
          withCredentials: true
        },
        success: function(data) {
          var has_graphs = 0;
          jQuery('#histou_source_select').find('option').remove();
          if(data && data["dashboard"] && data["dashboard"]["panels"]) {
            jQuery(data.dashboard.panels).each(function(j, panel) {
              jQuery('#histou_source_select').append('<option value="'+panel.id+'"'+((panel.id==histou_source || panel.title.match(histou_source)) ? ' selected' : '')+'>'+panel.title+'<\/option>');
              has_graphs++;
            });
          }
          if(has_graphs > 1) {
            jQuery('#histou_source_select').show();
          } else {
            jQuery('#histou_source_select').hide();
          }
        },
        error: ajax_xhr_error_logonly
      });
    }
  }
</script>
<div class="card w-full max-w-[800px] mx-auto overflow-hidden">
  <div class="head justify-between">
    <h3>Performance Graph</h3>
    <div class='pnpSelector'>
      <form action="#">
        <select onchange="histou_source=this.value; set_histou_img();" id="histou_source_select" style="display: none;">
        </select>
      </form>
    </div>
  </div>

  <div class="head px-0 clickable">
    <span                 class="tabs text-center w-12"    onclick="return move_histou_img(-0.5)"><i class="uil uil-angle-left text-lg contents"></i></span>
    <span id="histou_th1" class="tabs text-center w-[18%]" onclick="return set_histou_img(   -14400, '', this.id, histou_source)">4 hours</span>
    <span id="histou_th2" class="tabs text-center w-[18%]" onclick="return set_histou_img(   -90000, '', this.id, histou_source)">day</span>
    <span id="histou_th3" class="tabs text-center w-[18%]" onclick="return set_histou_img(  -540000, '', this.id, histou_source)">week</span>
    <span id="histou_th4" class="tabs text-center w-[18%]" onclick="return set_histou_img( -2764800, '', this.id, histou_source)">month</span>
    <span id="histou_th5" class="tabs text-center w-[18%]" onclick="return set_histou_img(-30067200, '', this.id, histou_source)">year</span>
    <span                 class="tabs text-center w-12"    onclick="return move_histou_img( 0.5)"><i class="uil uil-angle-right text-lg contents"></i></span>
  </div>
  <div class="h-[262px] relative justify-center">
    <a id="histou_graph_link" href="[% url_prefix %]#[% histou_url %]" class="clickable absolute top-0 left-0 w-full h-full z-40"></a>
    <div id="histou_graph_pane" style="display:none;" class="relative w-full h-full overflow-hidden">
      <div id="pnpwaitimg" class="absolute top-10 left-1/2 transform -translate-x-1/2" title="waiting"><div class="spinner w-12 h-12"></div></div>
      <iframe id="histou_iframe" src="[% histou_frame_url %]" class="w-full h-[270px] p-0 m-0 mx-auto"></iframe>
    </div>
  </div>
</div>

<script>
  var histou_id     = 'histou_th2';
  var histou_start  = [% date.now - 90000 %];
  var histou_end    = [% date.now %];
  if(window.location.hash != '#') {
    var values = window.location.hash.split("/");
    if(values[0]) {
      histou_id = values[0].replace(/^#/, '');
    }
    if(values[1]) {
      histou_start = values[1];
    }
    if(values[2]) {
      histou_end = values[2];
    }
    if(values[3] != undefined) {
      histou_source = values[3];
    }
  }


  if(jQuery.isNumeric(histou_source)) {
    set_histou_img(histou_start, histou_end, histou_id, histou_source, true);
  } else {
    jQuery('#pnpwaitimg').css('display', 'block');

    var hst   = '[% escape_js(hst) %]';
    var svc   = '[% escape_js(svc) %]';
    var grafana_default_panelId = "[% c.config.grafana_default_panelId %]";
    if(grafana_default_panelId == "") {
        grafana_default_panelId = "1";
    }

    // fetch id for source name
    if(histou_url.match("/script/histou.js")) {
      fetchHistouPanelId(histou_url, histou_source, hst, svc, function(newId) {
        if(newId === null) {
          set_histou_img(histou_start, histou_end, histou_source, grafana_default_panelId);
        } else {
          histou_source = ""+newId; // make refresh use the extracted id
          set_histou_img(histou_start, histou_end, histou_source, newId);
        }
      });
    } else {
      // extract panels from plain grafana dashboard
      var matches = histou_url.match(/(?:d|d-solo|dashboard)\/([^\/]+)\//);
      if(matches && matches[1]) {
        var source_url = histou_url;
        var dashboard_id = matches[1];
        var api_url = source_url.replace(/\/grafana\/.*$/, '/grafana/api/dashboards/uid/'+dashboard_id)
        jQuery.ajax({
          url: api_url,
          type: 'GET',
          xhrFields: {
            withCredentials: true
          },
          success: function(data) {
            if(data && data["dashboard"] && data["dashboard"]["panels"]) {
              jQuery(data.dashboard.panels).each(function(j, panel) {
                if(panel.id==histou_source || panel.title.match(histou_source)) {
                  histou_source = panel.id; // make refreses use the extracted id
                  set_histou_img(histou_start, histou_end, histou_id, panel.id);
                }
              });
            }
          },
          error: ajax_xhr_error_logonly
        });
      }
    }
  }
</script>
