1import { DataFrame } from '@grafana/data';
2import { DimensionSupplier, ResourceDimensionConfig, ResourceDimensionMode } from './types';
3import { findField, getLastNotNullFieldValue } from './utils';
4
5//---------------------------------------------------------
6// Resource dimension
7//---------------------------------------------------------
8export function getPublicOrAbsoluteUrl(v: string): string {
9  if (!v) {
10    return '';
11  }
12  return v.indexOf(':/') > 0 ? v : (window as any).__grafana_public_path__ + v;
13}
14
15export function getResourceDimension(
16  frame: DataFrame | undefined,
17  config: ResourceDimensionConfig
18): DimensionSupplier<string> {
19  const mode = config.mode ?? ResourceDimensionMode.Fixed;
20  if (mode === ResourceDimensionMode.Fixed) {
21    const v = getPublicOrAbsoluteUrl(config.fixed!);
22    return {
23      isAssumed: !Boolean(v),
24      fixed: v,
25      value: () => v,
26      get: (i) => v,
27    };
28  }
29
30  const field = findField(frame, config.field);
31  if (!field) {
32    const v = '';
33    return {
34      isAssumed: true,
35      fixed: v,
36      value: () => v,
37      get: (i) => v,
38    };
39  }
40
41  if (mode === ResourceDimensionMode.Mapping) {
42    const mapper = (v: any) => getPublicOrAbsoluteUrl(`${v}`);
43    return {
44      field,
45      get: (i) => mapper(field.values.get(i)),
46      value: () => mapper(getLastNotNullFieldValue(field)),
47    };
48  }
49
50  return {
51    field,
52    get: field.values.get,
53    value: () => getLastNotNullFieldValue(field),
54  };
55}
56