import { locationUtil } from '@grafana/data';
import { locationService } from '@grafana/runtime';
import { sceneGraph, VizPanel } from '@grafana/scenes';
import { contextSrv } from 'app/core/services/context_srv';
import { getExploreUrl } from 'app/core/utils/explore';

import { getDatasourceFromQueryRunner, getQueryRunnerFor } from './utils';

export function getViewPanelUrl(vizPanel: VizPanel) {
  return locationUtil.getUrlForPartial(locationService.getLocation(), {
    viewPanel: vizPanel.getPathId(),
    editPanel: undefined,
  });
}

export function getEditPanelUrl(panelId: number) {
  return locationUtil.getUrlForPartial(locationService.getLocation(), { editPanel: panelId, viewPanel: undefined });
}

export function tryGetExploreUrlForPanel(vizPanel: VizPanel): Promise<string | undefined> {
  //const dashboard = panel.getRoot();
  const panelPlugin = vizPanel.getPlugin();
  const queryRunner = getQueryRunnerFor(vizPanel);

  if (!contextSrv.hasAccessToExplore() || panelPlugin?.meta.skipDataQuery || !queryRunner) {
    return Promise.resolve(undefined);
  }

  const timeRange = sceneGraph.getTimeRange(vizPanel);
  const datasource = getDatasourceFromQueryRunner(queryRunner);

  return getExploreUrl({
    queries: queryRunner.state.queries,
    dsRef: datasource,
    timeRange: timeRange.state.value,
    scopedVars: { __sceneObject: { value: vizPanel } },
    adhocFilters: queryRunner.state.data?.request?.filters,
  });
}
