<commit_before>import coreModule from 'app/core/core_module';
import _ from 'lodash';
import { FilterSegments } from './filter_segments';
import appEvents from 'app/core/app_events';

export class StackdriverFilter {
  /** @ngInject */
  constructor() {
    return {
      templateUrl: 'public/app/plugins/datasource/stackdriver/partials/query.filter.html',
      controller: 'StackdriverFilterCtrl',
      controllerAs: 'ctrl',
      restrict: 'E',
      scope: {
        target: '=',
        datasource: '=',
        refresh: '&',
        hideGroupBys: '<',
      },
    };
  }
}

export class StackdriverFilterCtrl {
  metricLabels: { [key: string]: string[] };
  resourceLabels: { [key: string]: string[] };
  resourceTypes: string[];

  defaultRemoveGroupByValue = '-- remove group by --';
  resourceTypeValue = 'resource.type';
  loadLabelsPromise: Promise<any>;

  metricDescriptors: any[];
  metrics: any[];
  metricGroups: any[];
  services: any[];
  groupBySegments: any[];
  filterSegments: FilterSegments;
  removeSegment: any;
  target: any;
  datasource: any;

  /** @ngInject */
  constructor(private $scope, private uiSegmentSrv, private templateSrv, private $rootScope) {
    this.datasource = $scope.datasource;
    this.target = $scope.target;
    this.metricDescriptors = [];
    this.metrics = [];
    this.metricGroups = [];
    this.services = [];

    this.getCurrentProject()
      .then(this.loadMetricDescriptors.bind(this))
      .then(this.getLabels.bind(this));

    this.initSegments($scope.hideGroupBys);
    this.handleMetricTypeChange = this.handleMetricTypeChange.bind(this);
    this.handleServiceChange = this.handleServiceChange.bind(this);
  }

  handleMetricTypeChange(value) {
    this.target.metricType = value;
    this.onMetricTypeChange();
  }

  initSegments(hideGroupBys: boolean) {
    if (!hideGroupBys) {
      this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
        return this.uiSegmentSrv.getSegmentForValue(groupBy);
      });
      this.ensurePlusButton(this.groupBySegments);
    }

    this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });

    this.filterSegments = new FilterSegments(
      this.uiSegmentSrv,
      this.target,
      this.getFilterKeys.bind(this),
      this.getFilterValues.bind(this)
    );
    this.filterSegments.buildSegmentModel();
  }

  async getCurrentProject() {
    return new Promise(async (resolve, reject) => {
      try {
        if (!this.target.defaultProject || this.target.defaultProject === 'loading project...') {
          this.target.defaultProject = await this.datasource.getDefaultProject();
        }
        resolve(this.target.defaultProject);
      } catch (error) {
        appEvents.emit('ds-request-error', error);
        reject();
      }
    });
  }

  async loadMetricDescriptors() {
    if (this.target.defaultProject !== 'loading project...') {
      this.metricDescriptors = await this.datasource.getMetricTypes(this.target.defaultProject);
      this.services = this.getServicesList();
      this.metrics = this.getMetricsList();
      this.metricGroups = this.getMetricGroups();
      return this.metricDescriptors;
    } else {
      return [];
    }
  }

  getServicesList() {
    const services = this.metricDescriptors.map(m => ({
      value: m.service,
      label: _.startCase(m.serviceShortName),
    }));

    return services.length > 0 ? _.uniqBy(services, s => s.value) : [];
  }

  getMetricGroups() {
    return [
      this.getTemplateVariablesGroup(),
      {
        label: 'Metrics',
        options: this.getMetricsList(),
      },
    ];
  }

  getTemplateVariablesGroup() {
    return {
      label: 'Template Variables',
      options: this.templateSrv.variables.map(v => ({
        label: `$${v.name}`,
        value: `$${v.name}`,
      })),
    };
  }

  getMetricsList() {
    const metricsByService = this.metricDescriptors.filter(m => m.service === this.target.service).map(m => ({
      service: m.service,
      value: m.type,
      label: m.displayName,
      description: m.description,
    }));

    if (
      metricsByService.length > 0 &&
      !metricsByService.some(m => m.value === this.templateSrv.replace(this.target.metricType))
    ) {
      this.target.metricType = metricsByService[0].value;
    }
    return metricsByService;
  }

  async getLabels() {
    this.loadLabelsPromise = new Promise(async resolve => {
      try {
        if (this.target.metricType) {
          const { meta } = await this.datasource.getLabels(this.target.metricType, this.target.refId);
          this.metricLabels = meta.metricLabels;
          this.resourceLabels = meta.resourceLabels;
          this.resourceTypes = meta.resourceTypes;
          resolve();
        } else {
          resolve();
        }
      } catch (error) {
        if (error.data && error.data.message) {
          console.log(error.data.message);
        } else {
          console.log(error);
        }
        appEvents.emit('alert-error', ['Error', 'Error loading metric labels for ' + this.target.metricType]);
        resolve();
      }
    });
  }

  handleServiceChange(service) {
    this.target.service = service;
    this.metrics = this.getMetricsList();
    this.metricGroups = this.getMetricGroups();
    this.setMetricType();
    this.getLabels();
    if (!this.metrics.some(m => m.value === this.target.metricType)) {
      this.target.metricType = '';
    } else {
      this.$scope.refresh();
    }
  }

  async onMetricTypeChange() {
    this.setMetricType();
    this.$scope.refresh();
    this.getLabels();
  }

  setMetricType() {
    const { valueType, metricKind, unit } = this.metricDescriptors.find(
      m => m.type === this.templateSrv.replace(this.target.metricType)
    );
    this.target.unit = unit;
    this.target.valueType = valueType;<commit_msg>remove on metric type change<commit_after>import coreModule from 'app/core/core_module';
import _ from 'lodash';
import { FilterSegments } from './filter_segments';
import appEvents from 'app/core/app_events';

export class StackdriverFilter {
  /** @ngInject */
  constructor() {
    return {
      templateUrl: 'public/app/plugins/datasource/stackdriver/partials/query.filter.html',
      controller: 'StackdriverFilterCtrl',
      controllerAs: 'ctrl',
      restrict: 'E',
      scope: {
        target: '=',
        datasource: '=',
        refresh: '&',
        hideGroupBys: '<',
      },
    };
  }
}

export class StackdriverFilterCtrl {
  metricLabels: { [key: string]: string[] };
  resourceLabels: { [key: string]: string[] };
  resourceTypes: string[];

  defaultRemoveGroupByValue = '-- remove group by --';
  resourceTypeValue = 'resource.type';
  loadLabelsPromise: Promise<any>;

  metricDescriptors: any[];
  metrics: any[];
  metricGroups: any[];
  services: any[];
  groupBySegments: any[];
  filterSegments: FilterSegments;
  removeSegment: any;
  target: any;
  datasource: any;

  /** @ngInject */
  constructor(private $scope, private uiSegmentSrv, private templateSrv, private $rootScope) {
    this.datasource = $scope.datasource;
    this.target = $scope.target;
    this.metricDescriptors = [];
    this.metrics = [];
    this.metricGroups = [];
    this.services = [];

    this.getCurrentProject()
      .then(this.loadMetricDescriptors.bind(this))
      .then(this.getLabels.bind(this));

    this.initSegments($scope.hideGroupBys);
    this.handleMetricTypeChange = this.handleMetricTypeChange.bind(this);
    this.handleServiceChange = this.handleServiceChange.bind(this);
  }

  handleMetricTypeChange(value) {
    this.target.metricType = value;
    this.setMetricType();
    this.$scope.refresh();
    this.getLabels();
  }

  initSegments(hideGroupBys: boolean) {
    if (!hideGroupBys) {
      this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
        return this.uiSegmentSrv.getSegmentForValue(groupBy);
      });
      this.ensurePlusButton(this.groupBySegments);
    }

    this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });

    this.filterSegments = new FilterSegments(
      this.uiSegmentSrv,
      this.target,
      this.getFilterKeys.bind(this),
      this.getFilterValues.bind(this)
    );
    this.filterSegments.buildSegmentModel();
  }

  async getCurrentProject() {
    return new Promise(async (resolve, reject) => {
      try {
        if (!this.target.defaultProject || this.target.defaultProject === 'loading project...') {
          this.target.defaultProject = await this.datasource.getDefaultProject();
        }
        resolve(this.target.defaultProject);
      } catch (error) {
        appEvents.emit('ds-request-error', error);
        reject();
      }
    });
  }

  async loadMetricDescriptors() {
    if (this.target.defaultProject !== 'loading project...') {
      this.metricDescriptors = await this.datasource.getMetricTypes(this.target.defaultProject);
      this.services = this.getServicesList();
      this.metrics = this.getMetricsList();
      this.metricGroups = this.getMetricGroups();
      return this.metricDescriptors;
    } else {
      return [];
    }
  }

  getServicesList() {
    const services = this.metricDescriptors.map(m => ({
      value: m.service,
      label: _.startCase(m.serviceShortName),
    }));

    return services.length > 0 ? _.uniqBy(services, s => s.value) : [];
  }

  getMetricGroups() {
    return [
      this.getTemplateVariablesGroup(),
      {
        label: 'Metrics',
        options: this.getMetricsList(),
      },
    ];
  }

  getTemplateVariablesGroup() {
    return {
      label: 'Template Variables',
      options: this.templateSrv.variables.map(v => ({
        label: `$${v.name}`,
        value: `$${v.name}`,
      })),
    };
  }

  getMetricsList() {
    const metricsByService = this.metricDescriptors.filter(m => m.service === this.target.service).map(m => ({
      service: m.service,
      value: m.type,
      label: m.displayName,
      description: m.description,
    }));

    if (
      metricsByService.length > 0 &&
      !metricsByService.some(m => m.value === this.templateSrv.replace(this.target.metricType))
    ) {
      this.target.metricType = metricsByService[0].value;
    }
    return metricsByService;
  }

  async getLabels() {
    this.loadLabelsPromise = new Promise(async resolve => {
      try {
        if (this.target.metricType) {
          const { meta } = await this.datasource.getLabels(this.target.metricType, this.target.refId);
          this.metricLabels = meta.metricLabels;
          this.resourceLabels = meta.resourceLabels;
          this.resourceTypes = meta.resourceTypes;
          resolve();
        } else {
          resolve();
        }
      } catch (error) {
        if (error.data && error.data.message) {
          console.log(error.data.message);
        } else {
          console.log(error);
        }
        appEvents.emit('alert-error', ['Error', 'Error loading metric labels for ' + this.target.metricType]);
        resolve();
      }
    });
  }

  handleServiceChange(service) {
    this.target.service = service;
    this.metrics = this.getMetricsList();
    this.metricGroups = this.getMetricGroups();
    this.setMetricType();
    this.getLabels();
    if (!this.metrics.some(m => m.value === this.target.metricType)) {
      this.target.metricType = '';
    } else {
      this.$scope.refresh();
    }
  }

  setMetricType() {
    const { valueType, metricKind, unit } = this.metricDescriptors.find(
      m => m.type === this.templateSrv.replace(this.target.metricType)
    );
    this.target.unit = unit;
    this.target.valueType = valueType;
{'fraction_non_alphanumeric': 0.1406570841889117, 'fraction_numerical': 0.000513347022587269, 'mean_word_length': 2.8050130208333335, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '256381', 'n_tokens_mistral': 3535, 'n_tokens_neox': 3512, 'n_words': 596}