Загрузка данных


export const PRICE_AXIS_LABEL_HEIGHT = 20;

export type PriceAxisLabelStyle = 'filled' | 'outlined';

export interface PriceAxisLabel {
  id: string;
  collisionGroup: string;
  desiredCoordinate: number;
  text: string;
  color: string;
  style: PriceAxisLabelStyle;
  priority?: number;
  height?: number;
}

export interface LaidOutPriceAxisLabel extends PriceAxisLabel {
  coordinate: number;
  height: number;
}

export interface PriceAxisLabelsLayoutOptions {
  gap?: number;
  duplicateTolerance?: number;
}



import { getThemeStore } from '@src/theme';

import { layoutPriceAxisLabels } from './layout';

import type { CanvasRenderingTarget2D } from 'fancy-canvas';
import type {
  ChartOptions,
  IPrimitivePaneRenderer,
  IPrimitivePaneView,
  ISeriesPrimitive,
  PrimitivePaneViewZOrder,
  SeriesAttachedParameter,
  Time,
} from 'lightweight-charts';
import type { LaidOutPriceAxisLabel, PriceAxisLabel } from './types';

type PriceAxisSide = 'left' | 'right';
type ChartLayoutOptions = Readonly<ChartOptions['layout']>;

interface MeasuredLabel {
  label: PriceAxisLabel;
  text: string;
  width: number;
  height: number;
  ascent: number;
  descent: number;
}

interface LabelGeometry {
  label: LaidOutPriceAxisLabel;
  text: string;
  left: number;
  top: number;
  width: number;
  height: number;
  textX: number;
  textY: number;
}

const HORIZONTAL_PADDING_RATIO = 7.25 / 12;
const VERTICAL_PADDING_RATIO = 3 / 12;
const TEXT_VERTICAL_OFFSET_RATIO = 1 / 12;
const CONTRAST_THRESHOLD = 160;

function parseColor(color: string): [number, number, number] | null {
  const normalizedColor = color.trim();

  if (normalizedColor.startsWith('#')) {
    const hex = normalizedColor.slice(1);

    if (hex.length === 3 || hex.length === 4) {
      const red = Number.parseInt(`${hex[0]}${hex[0]}`, 16);

      const green = Number.parseInt(`${hex[1]}${hex[1]}`, 16);

      const blue = Number.parseInt(`${hex[2]}${hex[2]}`, 16);

      if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
        return null;
      }

      return [red, green, blue];
    }

    if (hex.length === 6 || hex.length === 8) {
      const red = Number.parseInt(hex.slice(0, 2), 16);

      const green = Number.parseInt(hex.slice(2, 4), 16);

      const blue = Number.parseInt(hex.slice(4, 6), 16);

      if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
        return null;
      }

      return [red, green, blue];
    }

    return null;
  }

  const rgbMatch = normalizedColor.match(/^rgba?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)/i);

  if (!rgbMatch) {
    return null;
  }

  const red = Number(rgbMatch[1]);
  const green = Number(rgbMatch[2]);
  const blue = Number(rgbMatch[3]);

  if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
    return null;
  }

  return [red, green, blue];
}

function normalizeCanvasColor(context: CanvasRenderingContext2D, color: string): string {
  const previousFillStyle = context.fillStyle;

  context.fillStyle = '#000000';
  context.fillStyle = color;

  const normalizedColor = String(context.fillStyle);

  context.fillStyle = previousFillStyle;

  return normalizedColor;
}

function getFilledLabelTextColor(context: CanvasRenderingContext2D, color: string): string {
  const normalizedColor = normalizeCanvasColor(context, color);

  const rgb = parseColor(normalizedColor);

  if (!rgb) {
    return '#FFFFFF';
  }

  const [red, green, blue] = rgb;

  const grayscale = 0.199 * red + 0.687 * green + 0.114 * blue;

  return grayscale > CONTRAST_THRESHOLD ? '#000000' : '#FFFFFF';
}

function getLabelTextColor(context: CanvasRenderingContext2D, label: PriceAxisLabel): string {
  if (label.style === 'outlined') {
    return label.color;
  }

  return getFilledLabelTextColor(context, label.color);
}

function areLabelsEqual(currentLabels: readonly PriceAxisLabel[], nextLabels: readonly PriceAxisLabel[]): boolean {
  if (currentLabels.length !== nextLabels.length) {
    return false;
  }

  return currentLabels.every((currentLabel, index) => {
    const nextLabel = nextLabels[index];

    return (
      currentLabel.id === nextLabel.id &&
      currentLabel.collisionGroup === nextLabel.collisionGroup &&
      currentLabel.desiredCoordinate === nextLabel.desiredCoordinate &&
      currentLabel.text === nextLabel.text &&
      currentLabel.color === nextLabel.color &&
      currentLabel.style === nextLabel.style &&
      currentLabel.priority === nextLabel.priority
    );
  });
}

function getFont(layout: ChartLayoutOptions): string {
  return `${layout.fontSize}px ${layout.fontFamily}`;
}

function getHorizontalPadding(layout: ChartLayoutOptions): number {
  return layout.fontSize * HORIZONTAL_PADDING_RATIO;
}

function getVerticalPadding(layout: ChartLayoutOptions): number {
  return layout.fontSize * VERTICAL_PADDING_RATIO;
}

function getTextVerticalOffset(layout: ChartLayoutOptions): number {
  return layout.fontSize * TEXT_VERTICAL_OFFSET_RATIO;
}

function getLabelLeft(side: PriceAxisSide, axisWidth: number, labelWidth: number): number {
  return side === 'right' ? 0 : axisWidth - labelWidth;
}

function measureLabels(
  context: CanvasRenderingContext2D,
  labels: readonly PriceAxisLabel[],
  layout: ChartLayoutOptions,
): MeasuredLabel[] {
  const horizontalPadding = getHorizontalPadding(layout);

  const verticalPadding = getVerticalPadding(layout);

  return labels.map((label) => {
    const textMetrics = context.measureText(label.text);

    const ascent = textMetrics.actualBoundingBoxAscent || layout.fontSize * 0.75;

    const descent = textMetrics.actualBoundingBoxDescent || layout.fontSize * 0.25;

    const textWidth = Math.ceil(textMetrics.width);

    const textHeight = ascent + descent;

    return {
      label,
      text: label.text,
      width: textWidth + horizontalPadding * 2,
      height: textHeight + verticalPadding * 2,
      ascent,
      descent,
    };
  });
}

function createLabelGeometries(
  measuredLabels: readonly MeasuredLabel[],
  axisWidth: number,
  axisHeight: number,
  side: PriceAxisSide,
  layout: ChartLayoutOptions,
): LabelGeometry[] {
  const labelsWithMeasuredHeight = measuredLabels.map(({ label, height }) => ({
    ...label,
    height,
  }));

  const laidOutLabels = layoutPriceAxisLabels(labelsWithMeasuredHeight, axisHeight);

  const measuredLabelsById = new Map(
    measuredLabels.map((measuredLabel) => [measuredLabel.label.id, measuredLabel] as const),
  );

  const verticalOffset = getTextVerticalOffset(layout);

  return laidOutLabels.flatMap((label) => {
    const measuredLabel = measuredLabelsById.get(label.id);

    if (!measuredLabel) {
      return [];
    }

    const { width, height, ascent, descent } = measuredLabel;

    const left = getLabelLeft(side, axisWidth, width);

    const top = label.coordinate - height / 2;

    return [
      {
        label,
        text: measuredLabel.text,
        left,
        top,
        width,
        height,
        textX: left + width / 2,
        textY: label.coordinate + (ascent - descent) / 2 + verticalOffset,
      },
    ];
  });
}

function drawLabelBackgrounds(target: CanvasRenderingTarget2D, geometries: readonly LabelGeometry[]): void {
  target.useBitmapCoordinateSpace(({ context, horizontalPixelRatio, verticalPixelRatio }) => {
    const { colors } = getThemeStore();

    context.save();

    geometries.forEach(({ label, left, top, width, height }) => {
      const bitmapLeft = Math.round(left * horizontalPixelRatio);

      const bitmapTop = Math.round(top * verticalPixelRatio);

      const bitmapWidth = Math.round(width * horizontalPixelRatio);

      const bitmapHeight = Math.round(height * verticalPixelRatio);

      const backgroundColor = label.style === 'outlined' ? colors.chartBackground : label.color;

      context.fillStyle = backgroundColor;

      context.fillRect(bitmapLeft, bitmapTop, bitmapWidth, bitmapHeight);

      if (label.style !== 'outlined') {
        return;
      }

      const borderWidth = Math.max(1, Math.floor(Math.min(horizontalPixelRatio, verticalPixelRatio)));

      context.strokeStyle = label.color;

      context.lineWidth = borderWidth;

      context.strokeRect(
        bitmapLeft + borderWidth / 2,
        bitmapTop + borderWidth / 2,
        Math.max(0, bitmapWidth - borderWidth),
        Math.max(0, bitmapHeight - borderWidth),
      );
    });

    context.restore();
  });
}

function drawLabelTexts(
  target: CanvasRenderingTarget2D,
  geometries: readonly LabelGeometry[],
  layout: ChartLayoutOptions,
): void {
  target.useMediaCoordinateSpace(({ context }) => {
    context.save();

    context.font = getFont(layout);

    context.textAlign = 'center';
    context.textBaseline = 'alphabetic';

    geometries.forEach(({ label, text, textX, textY }) => {
      context.fillStyle = getLabelTextColor(context, label);

      context.fillText(text, textX, textY);
    });

    context.restore();
  });
}

class PriceAxisLabelsRenderer implements IPrimitivePaneRenderer {
  constructor(
    private readonly getLabels: () => readonly PriceAxisLabel[],
    private readonly getLayout: () => ChartLayoutOptions | null,
    private readonly getSide: () => PriceAxisSide,
    private readonly requestMinimumWidth: (width: number) => void,
  ) {}

  public draw(target: CanvasRenderingTarget2D): void {
    const labels = this.getLabels();
    const layout = this.getLayout();

    if (labels.length === 0 || !layout) {
      return;
    }

    let geometries: LabelGeometry[] = [];

    target.useMediaCoordinateSpace(({ context, mediaSize }) => {
      if (mediaSize.width <= 0 || mediaSize.height <= 0) {
        return;
      }

      context.save();
      context.font = getFont(layout);

      const measuredLabels = measureLabels(context, labels, layout);

      const requiredWidth = measuredLabels.reduce((maximumWidth, label) => Math.max(maximumWidth, label.width), 0);

      this.requestMinimumWidth(requiredWidth);

      geometries = createLabelGeometries(measuredLabels, mediaSize.width, mediaSize.height, this.getSide(), layout);

      context.restore();
    });

    if (geometries.length === 0) {
      return;
    }

    drawLabelBackgrounds(target, geometries);

    drawLabelTexts(target, geometries, layout);
  }
}

class PriceAxisLabelsPaneView implements IPrimitivePaneView {
  private readonly rendererInstance: PriceAxisLabelsRenderer;

  constructor(
    private readonly getLabels: () => readonly PriceAxisLabel[],
    getLayout: () => ChartLayoutOptions | null,
    getSide: () => PriceAxisSide,
    requestMinimumWidth: (width: number) => void,
  ) {
    this.rendererInstance = new PriceAxisLabelsRenderer(getLabels, getLayout, getSide, requestMinimumWidth);
  }

  public renderer(): IPrimitivePaneRenderer | null {
    return this.getLabels().length > 0 ? this.rendererInstance : null;
  }

  public zOrder(): PrimitivePaneViewZOrder {
    return 'top';
  }
}

export class PriceAxisLabelsPrimitive implements ISeriesPrimitive<Time> {
  private readonly priceAxisPaneView: PriceAxisLabelsPaneView;

  private readonly priceAxisPaneViewList: readonly IPrimitivePaneView[];

  private labels: readonly PriceAxisLabel[] = [];

  private chart: SeriesAttachedParameter<Time>['chart'] | null = null;

  private series: SeriesAttachedParameter<Time>['series'] | null = null;

  private requestUpdate: (() => void) | null = null;

  private initialMinimumWidth = 0;

  private appliedMinimumWidth = 0;

  private pendingMinimumWidth: number | null = null;

  private minimumWidthFrame: number | null = null;

  constructor() {
    this.priceAxisPaneView = new PriceAxisLabelsPaneView(
      () => this.labels,
      () => this.chart?.options().layout ?? null,
      () => (this.series?.options().priceScaleId === 'left' ? 'left' : 'right'),
      (width) => {
        this.scheduleMinimumWidthUpdate(width);
      },
    );

    this.priceAxisPaneViewList = [this.priceAxisPaneView];
  }

  public attached({ chart, series, requestUpdate }: SeriesAttachedParameter<Time>): void {
    this.chart = chart;
    this.series = series;
    this.requestUpdate = requestUpdate;

    this.initialMinimumWidth = series.priceScale().options().minimumWidth ?? 0;

    this.appliedMinimumWidth = this.initialMinimumWidth;

    this.requestUpdate();
  }

  public detached(): void {
    this.cancelMinimumWidthUpdate();

    this.applyMinimumWidth(this.initialMinimumWidth);

    this.chart = null;
    this.series = null;
    this.requestUpdate = null;
    this.pendingMinimumWidth = null;
    this.initialMinimumWidth = 0;
    this.appliedMinimumWidth = 0;
  }

  public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
    return this.priceAxisPaneViewList;
  }

  public updateAllViews(): void {}

  public setLabels(labels: readonly PriceAxisLabel[]): void {
    if (areLabelsEqual(this.labels, labels)) {
      return;
    }

    this.labels = labels;

    if (labels.length === 0) {
      this.scheduleMinimumWidthUpdate(0);
    }

    this.requestUpdate?.();
  }

  public clear(): void {
    if (this.labels.length === 0) {
      return;
    }

    this.labels = [];

    this.scheduleMinimumWidthUpdate(0);
    this.requestUpdate?.();
  }

  private scheduleMinimumWidthUpdate(requiredWidth: number): void {
    const nextMinimumWidth = Math.max(this.initialMinimumWidth, Math.ceil(requiredWidth));

    if (nextMinimumWidth === this.appliedMinimumWidth || nextMinimumWidth === this.pendingMinimumWidth) {
      return;
    }

    this.pendingMinimumWidth = nextMinimumWidth;

    if (this.minimumWidthFrame !== null) {
      return;
    }

    if (typeof requestAnimationFrame !== 'function') {
      this.flushMinimumWidthUpdate();

      return;
    }

    this.minimumWidthFrame = requestAnimationFrame(() => {
      this.minimumWidthFrame = null;

      this.flushMinimumWidthUpdate();
    });
  }

  private flushMinimumWidthUpdate(): void {
    const nextMinimumWidth = this.pendingMinimumWidth;

    this.pendingMinimumWidth = null;

    if (nextMinimumWidth === null) {
      return;
    }

    this.applyMinimumWidth(nextMinimumWidth);
  }

  private applyMinimumWidth(minimumWidth: number): void {
    if (!this.series || minimumWidth === this.appliedMinimumWidth) {
      return;
    }

    this.series.priceScale().applyOptions({
      minimumWidth,
    });

    this.appliedMinimumWidth = minimumWidth;
  }

  private cancelMinimumWidthUpdate(): void {
    if (this.minimumWidthFrame === null) {
      return;
    }

    if (typeof cancelAnimationFrame === 'function') {
      cancelAnimationFrame(this.minimumWidthFrame);
    }

    this.minimumWidthFrame = null;
    this.pendingMinimumWidth = null;
  }
}


import { LaidOutPriceAxisLabel, PRICE_AXIS_LABEL_HEIGHT, PriceAxisLabel, PriceAxisLabelsLayoutOptions } from './types';

const DEFAULT_LABEL_GAP = 2;
const DEFAULT_DUPLICATE_TOLERANCE = 1;

function compareLabels(left: PriceAxisLabel, right: PriceAxisLabel): number {
  if (left.desiredCoordinate !== right.desiredCoordinate) {
    return left.desiredCoordinate - right.desiredCoordinate;
  }

  const priorityDiff = (right.priority ?? 0) - (left.priority ?? 0);

  if (priorityDiff !== 0) {
    return priorityDiff;
  }

  return left.id.localeCompare(right.id);
}

function isDuplicate(left: PriceAxisLabel, right: PriceAxisLabel, tolerance: number): boolean {
  return left.text === right.text && Math.abs(left.desiredCoordinate - right.desiredCoordinate) <= tolerance;
}

function deduplicateLabels(labels: readonly PriceAxisLabel[], tolerance: number): PriceAxisLabel[] {
  const sortedLabels = [...labels].sort((left, right) => {
    const priorityDiff = (right.priority ?? 0) - (left.priority ?? 0);

    if (priorityDiff !== 0) {
      return priorityDiff;
    }

    return left.id.localeCompare(right.id);
  });

  const result: PriceAxisLabel[] = [];

  sortedLabels.forEach((label) => {
    const duplicateExists = result.some((currentLabel) => isDuplicate(currentLabel, label, tolerance));

    if (!duplicateExists) {
      result.push(label);
    }
  });

  return result;
}

function createLaidOutLabel(label: PriceAxisLabel, coordinate: number): LaidOutPriceAxisLabel {
  return {
    ...label,
    coordinate,
    height: label.height ?? PRICE_AXIS_LABEL_HEIGHT,
  };
}

function distributeLabelsInsideSmallAxis(
  labels: readonly PriceAxisLabel[],
  axisHeight: number,
): LaidOutPriceAxisLabel[] {
  if (labels.length === 0) {
    return [];
  }

  if (labels.length === 1) {
    const label = labels[0];
    const height = label.height ?? PRICE_AXIS_LABEL_HEIGHT;
    const minCoordinate = height / 2;
    const maxCoordinate = Math.max(minCoordinate, axisHeight - height / 2);

    return [createLaidOutLabel(label, Math.min(Math.max(label.desiredCoordinate, minCoordinate), maxCoordinate))];
  }

  const firstHeight = labels[0].height ?? PRICE_AXIS_LABEL_HEIGHT;
  const lastHeight = labels[labels.length - 1].height ?? PRICE_AXIS_LABEL_HEIGHT;
  const minCoordinate = firstHeight / 2;
  const maxCoordinate = Math.max(minCoordinate, axisHeight - lastHeight / 2);
  const step = Math.max(0, (maxCoordinate - minCoordinate) / (labels.length - 1));

  return labels.map((label, index) => createLaidOutLabel(label, minCoordinate + step * index));
}

function resolveCollisionGroup(
  labels: readonly PriceAxisLabel[],
  axisHeight: number,
  gap: number,
): LaidOutPriceAxisLabel[] {
  const sortedLabels = [...labels].sort(compareLabels);

  if (sortedLabels.length === 0) {
    return [];
  }

  const totalLabelsHeight = sortedLabels.reduce((total, label) => total + (label.height ?? PRICE_AXIS_LABEL_HEIGHT), 0);

  if (totalLabelsHeight > axisHeight) {
    return distributeLabelsInsideSmallAxis(sortedLabels, axisHeight);
  }

  const maxAvailableGap =
    sortedLabels.length > 1 ? Math.max(0, (axisHeight - totalLabelsHeight) / (sortedLabels.length - 1)) : gap;
  const effectiveGap = Math.min(gap, maxAvailableGap);

  const resolvedLabels = sortedLabels.map((label) => {
    const height = label.height ?? PRICE_AXIS_LABEL_HEIGHT;
    const minCoordinate = height / 2;
    const maxCoordinate = Math.max(minCoordinate, axisHeight - height / 2);

    return createLaidOutLabel(label, Math.min(Math.max(label.desiredCoordinate, minCoordinate), maxCoordinate));
  });

  for (let index = 1; index < resolvedLabels.length; index += 1) {
    const previousLabel = resolvedLabels[index - 1];
    const currentLabel = resolvedLabels[index];
    const minCoordinate = previousLabel.coordinate + previousLabel.height / 2 + currentLabel.height / 2 + effectiveGap;

    if (currentLabel.coordinate < minCoordinate) {
      currentLabel.coordinate = minCoordinate;
    }
  }

  const lastLabel = resolvedLabels[resolvedLabels.length - 1];
  const lastMaxCoordinate = axisHeight - lastLabel.height / 2;

  if (lastLabel.coordinate > lastMaxCoordinate) {
    const offset = lastLabel.coordinate - lastMaxCoordinate;

    resolvedLabels.forEach((label) => {
      label.coordinate -= offset;
    });
  }

  for (let index = resolvedLabels.length - 2; index >= 0; index -= 1) {
    const currentLabel = resolvedLabels[index];
    const nextLabel = resolvedLabels[index + 1];
    const maxCoordinate = nextLabel.coordinate - nextLabel.height / 2 - currentLabel.height / 2 - effectiveGap;

    if (currentLabel.coordinate > maxCoordinate) {
      currentLabel.coordinate = maxCoordinate;
    }
  }

  const firstLabel = resolvedLabels[0];
  const firstMinCoordinate = firstLabel.height / 2;

  if (firstLabel.coordinate < firstMinCoordinate) {
    const offset = firstMinCoordinate - firstLabel.coordinate;

    resolvedLabels.forEach((label) => {
      label.coordinate += offset;
    });
  }

  return resolvedLabels;
}

export function layoutPriceAxisLabels(
  labels: readonly PriceAxisLabel[],
  axisHeight: number,
  options: PriceAxisLabelsLayoutOptions = {},
): LaidOutPriceAxisLabel[] {
  if (axisHeight <= 0 || labels.length === 0) {
    return [];
  }

  const gap = options.gap ?? DEFAULT_LABEL_GAP;
  const duplicateTolerance = options.duplicateTolerance ?? DEFAULT_DUPLICATE_TOLERANCE;
  const labelsByCollisionGroup = new Map<string, PriceAxisLabel[]>();

  labels.forEach((label) => {
    if (!Number.isFinite(label.desiredCoordinate)) {
      return;
    }

    const group = labelsByCollisionGroup.get(label.collisionGroup);

    if (group) {
      group.push(label);
      return;
    }

    labelsByCollisionGroup.set(label.collisionGroup, [label]);
  });

  const result: LaidOutPriceAxisLabel[] = [];

  labelsByCollisionGroup.forEach((groupLabels) => {
    const uniqueLabels = deduplicateLabels(groupLabels, duplicateTolerance);

    result.push(...resolveCollisionGroup(uniqueLabels, axisHeight, gap));
  });

  return result.sort((left, right) => {
    const priorityDiff = (left.priority ?? 0) - (right.priority ?? 0);

    if (priorityDiff !== 0) {
      return priorityDiff;
    }

    return left.id.localeCompare(right.id);
  });
}


export { PriceAxisLabelsController } from './controller';
export { layoutPriceAxisLabels } from './layout';
export { PriceAxisLabelsPrimitive } from './primitive';
export type { LaidOutPriceAxisLabel, PriceAxisLabel, PriceAxisLabelsLayoutOptions, PriceAxisLabelStyle } from './types';


import { IPriceLine, LogicalRange, MismatchDirection, PriceScaleMode } from 'lightweight-charts';
import { Observable, Subscription } from 'rxjs';

import { Indicator } from '@core/Indicator';
import { IndicatorsIds, MAIN_PANE_INDEX } from '@src/constants';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { getThemeStore } from '@src/theme';
import { Direction } from '@src/types';
import { formatCompactNumber, formatPercent, formatPrice } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

import { PriceAxisLabelsPrimitive } from './primitive';
import { PRICE_AXIS_LABEL_HEIGHT, PriceAxisLabel } from './types';

type EntityCollection = 'compare' | 'indicator';
type SourceRole = 'main' | 'compare' | 'indicator' | 'volume';
type PriceAxisSide = Direction.Left | Direction.Right;

interface PriceAxisLabelsControllerOptions {
  mainSeries$: Observable<SeriesStrategies | null>;
  mainSymbol$: Observable<string>;
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

interface PriceLabelSource {
  id: string;
  role: SourceRole;
  series: SeriesStrategies;
  collisionGroup: string;
  priority: number;
}

interface SourceDefaults {
  lastValueVisible: boolean;
  priceLineVisible: boolean;
  title: string;
}

interface AxisLabelsGroup {
  paneIndex: number;
  side: PriceAxisSide;
  labels: PriceAxisLabel[];
}

interface AxisLayer {
  host: SeriesStrategies;
  primitive: PriceAxisLabelsPrimitive;
}

interface IndexedPriceAxisLabel {
  index: number;
  label: PriceAxisLabel;
}

const SOURCE_PRIORITY: Record<SourceRole, number> = {
  main: 100,
  compare: 80,
  indicator: 50,
  volume: 30,
};

const PRICE_AXIS_LABEL_GAP = 2;

function getDataPrice(data: unknown): number | null {
  if (!data || typeof data !== 'object') {
    return null;
  }

  if ('close' in data && typeof data.close === 'number') {
    return data.close;
  }

  if ('value' in data && typeof data.value === 'number') {
    return data.value;
  }

  return null;
}

function toOpaqueColor(color: string): string {
  return /^#[0-9a-fA-F]{8}$/.test(color) ? removeAlphaFromHex(color) : color;
}

function getSeriesColor(series: SeriesStrategies, data: unknown): string {
  if (data && typeof data === 'object' && 'color' in data && typeof data.color === 'string') {
    return toOpaqueColor(data.color);
  }

  const options = series.options() as unknown as Record<string, unknown>;

  if (
    data &&
    typeof data === 'object' &&
    'open' in data &&
    'close' in data &&
    typeof data.open === 'number' &&
    typeof data.close === 'number'
  ) {
    const candleColor = data.close >= data.open ? options.upColor : options.downColor;

    if (typeof candleColor === 'string') {
      return toOpaqueColor(candleColor);
    }
  }

  const color = [options.color, options.lineColor, options.topLineColor, options.bottomLineColor].find(
    (value): value is string => typeof value === 'string',
  );

  return color ? toOpaqueColor(color) : toOpaqueColor(getThemeStore().colors.chartLineColor);
}

function getContrastTextColor(color: string): string {
  const normalizedColor = toOpaqueColor(color).replace('#', '').slice(0, 6);

  if (normalizedColor.length !== 6) {
    return '#FFFFFF';
  }

  const red = Number.parseInt(normalizedColor.slice(0, 2), 16);
  const green = Number.parseInt(normalizedColor.slice(2, 4), 16);
  const blue = Number.parseInt(normalizedColor.slice(4, 6), 16);

  if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
    return '#FFFFFF';
  }

  const luminance = (red * 0.299 + green * 0.587 + blue * 0.114) / 255;

  return luminance > 0.6 ? '#000000' : '#FFFFFF';
}

function getShortSymbol(symbol: string): string {
  const parts = symbol.split(':');

  return parts[parts.length - 1] || symbol;
}

function getAxisSide(source: PriceLabelSource): PriceAxisSide {
  if (source.role === 'volume') {
    return Direction.Right;
  }

  return source.series.options().priceScaleId === Direction.Left ? Direction.Left : Direction.Right;
}

function getAxisKey(paneIndex: number, side: PriceAxisSide): string {
  return `${paneIndex}:${side}`;
}

function getEntityKey(collection: EntityCollection, entity: Indicator): string {
  return `${collection}:${entity.getId()}`;
}

function areSeriesListsEqual(
  currentSeries: readonly SeriesStrategies[] | undefined,
  nextSeries: readonly SeriesStrategies[],
): boolean {
  return (
    currentSeries?.length === nextSeries.length && currentSeries.every((series, index) => series === nextSeries[index])
  );
}

function getLabelHeight(label: PriceAxisLabel): number {
  return label.height || PRICE_AXIS_LABEL_HEIGHT;
}

function labelsIntersect(label: PriceAxisLabel, groupTop: number, groupBottom: number): boolean {
  const halfHeight = getLabelHeight(label) / 2;
  const labelTop = label.desiredCoordinate - halfHeight;
  const labelBottom = label.desiredCoordinate + halfHeight;

  return labelBottom + PRICE_AXIS_LABEL_GAP >= groupTop && labelTop - PRICE_AXIS_LABEL_GAP <= groupBottom;
}

function stackLabelsAboveReservedLabel(
  labels: readonly PriceAxisLabel[],
  reservedCoordinate: number,
): PriceAxisLabel[] {
  const reservedHalfHeight = PRICE_AXIS_LABEL_HEIGHT / 2;

  const reservedBottom = reservedCoordinate + reservedHalfHeight;

  let stackTop = reservedCoordinate - reservedHalfHeight;

  const pending: IndexedPriceAxisLabel[] = labels
    .map((label, index) => ({
      index,
      label,
    }))
    .sort((left, right) => {
      const leftDistance = Math.abs(left.label.desiredCoordinate - reservedCoordinate);

      const rightDistance = Math.abs(right.label.desiredCoordinate - reservedCoordinate);

      if (leftDistance !== rightDistance) {
        return leftDistance - rightDistance;
      }

      return right.label.priority! - left.label.priority!;
    });

  const resolvedCoordinates = new Map<number, number>();

  let hasNewStackedLabels = true;

  while (hasNewStackedLabels) {
    hasNewStackedLabels = false;

    for (let index = 0; index < pending.length; ) {
      const item = pending[index];

      if (!labelsIntersect(item.label, stackTop, reservedBottom)) {
        index += 1;

        continue;
      }

      const labelHeight = getLabelHeight(item.label);

      const coordinate = stackTop - PRICE_AXIS_LABEL_GAP - labelHeight / 2;

      resolvedCoordinates.set(item.index, coordinate);

      stackTop = coordinate - labelHeight / 2;

      pending.splice(index, 1);
      hasNewStackedLabels = true;
    }
  }

  return labels.map((label, index) => {
    const coordinate = resolvedCoordinates.get(index);

    if (coordinate === undefined) {
      return label;
    }

    return {
      ...label,
      desiredCoordinate: coordinate,
    };
  });
}

export class PriceAxisLabelsController {
  private readonly subscriptions = new Subscription();

  private readonly entitySubscriptions = new Map<string, Subscription>();

  private readonly entitySeries = new Map<string, readonly SeriesStrategies[]>();

  private readonly sourceDefaults = new WeakMap<SeriesStrategies, SourceDefaults>();

  private readonly layers = new Map<string, AxisLayer>();

  private mainSeries: SeriesStrategies | null = null;

  private mainSeriesDataHandler: (() => void) | null = null;

  private compareEntities: Indicator[] = [];

  private indicatorEntities: Indicator[] = [];

  private visibleLogicalRange: LogicalRange | null = null;

  private currentPriceLine: IPriceLine | null = null;

  private currentPriceLineHost: SeriesStrategies | null = null;

  private mainSymbol = '';

  private isHistoryMode = false;

  private updateFrame: number | null = null;

  constructor({ mainSeries$, mainSymbol$, compareEntities$, indicatorEntities$ }: PriceAxisLabelsControllerOptions) {
    this.subscriptions.add(
      mainSymbol$.subscribe((symbol) => {
        this.mainSymbol = getShortSymbol(symbol);

        this.applyDisplayMode();
        this.scheduleUpdate();
      }),
    );

    this.subscriptions.add(
      mainSeries$.subscribe((series) => {
        this.setMainSeries(series);
      }),
    );

    this.subscriptions.add(
      compareEntities$.subscribe((entities) => {
        this.setEntities('compare', entities);
      }),
    );

    this.subscriptions.add(
      indicatorEntities$.subscribe((entities) => {
        this.setEntities('indicator', entities);
      }),
    );
  }

  public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
    this.visibleLogicalRange = logicalRange;
    this.refreshHistoryMode();
    this.scheduleUpdate();
  }

  public invalidate(): void {
    this.scheduleUpdate();
  }

  public destroy(): void {
    if (this.updateFrame !== null && typeof cancelAnimationFrame === 'function') {
      cancelAnimationFrame(this.updateFrame);
      this.updateFrame = null;
    }

    this.unsubscribeMainSeries();
    this.subscriptions.unsubscribe();

    this.entitySubscriptions.forEach((subscription) => {
      subscription.unsubscribe();
    });

    this.getSources().forEach((source) => {
      this.restoreSourceOptions(source.series);
    });

    this.entitySubscriptions.clear();
    this.entitySeries.clear();

    this.layers.forEach(({ host, primitive }) => {
      try {
        host.detachPrimitive(primitive);
      } catch {
        // Серия могла быть удалена раньше контроллера.
      }
    });

    this.layers.clear();
    this.removeCurrentPriceLine();
  }

  private setMainSeries(series: SeriesStrategies | null): void {
    if (this.mainSeries === series) {
      return;
    }

    const previousSeries = this.mainSeries;

    this.unsubscribeMainSeries();

    if (previousSeries) {
      this.restoreSourceOptions(previousSeries);
    }

    this.mainSeries = series;

    if (series) {
      this.ensureSourceDefaults(series);

      this.mainSeriesDataHandler = () => {
        this.refreshHistoryMode();
        this.scheduleUpdate();
      };

      series.subscribeDataChanged(this.mainSeriesDataHandler);
    }

    if (this.currentPriceLineHost && this.currentPriceLineHost !== series) {
      this.removeCurrentPriceLine();
    }

    this.refreshHistoryMode();
    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private unsubscribeMainSeries(): void {
    if (!this.mainSeries || !this.mainSeriesDataHandler) {
      this.mainSeriesDataHandler = null;

      return;
    }

    try {
      this.mainSeries.unsubscribeDataChanged(this.mainSeriesDataHandler);
    } catch {
      // Серия могла быть удалена раньше контроллера.
    }

    this.mainSeriesDataHandler = null;
  }

  private setEntities(collection: EntityCollection, entities: Indicator[]): void {
    if (collection === 'compare') {
      this.compareEntities = entities;
    } else {
      this.indicatorEntities = entities;
    }

    this.syncEntitySubscriptions(collection, entities);

    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private syncEntitySubscriptions(collection: EntityCollection, entities: Indicator[]): void {
    const activeKeys = new Set(entities.map((entity) => getEntityKey(collection, entity)));

    this.entitySubscriptions.forEach((subscription, key) => {
      if (!key.startsWith(`${collection}:`) || activeKeys.has(key)) {
        return;
      }

      const removedSeries = this.entitySeries.get(key);

      removedSeries?.forEach((series) => {
        this.restoreSourceOptions(series);
      });

      subscription.unsubscribe();

      this.entitySubscriptions.delete(key);
      this.entitySeries.delete(key);
    });

    entities.forEach((entity) => {
      const key = getEntityKey(collection, entity);

      const nextSeries = Array.from(entity.getSeriesMap().values());

      const currentSeries = this.entitySeries.get(key);

      if (!areSeriesListsEqual(currentSeries, nextSeries)) {
        currentSeries
          ?.filter((series) => !nextSeries.includes(series))
          .forEach((series) => {
            this.restoreSourceOptions(series);
          });

        this.entitySeries.set(key, nextSeries);

        this.applyDisplayModeToSources(this.getEntitySources(collection, entity));
      }

      if (this.entitySubscriptions.has(key)) {
        return;
      }

      const subscription = entity.subscribeDataChange(() => {
        const updatedSeries = Array.from(entity.getSeriesMap().values());

        const registeredSeries = this.entitySeries.get(key);

        if (!areSeriesListsEqual(registeredSeries, updatedSeries)) {
          registeredSeries
            ?.filter((series) => !updatedSeries.includes(series))
            .forEach((series) => {
              this.restoreSourceOptions(series);
            });

          this.entitySeries.set(key, updatedSeries);

          this.applyDisplayModeToSources(this.getEntitySources(collection, entity));
        }

        this.scheduleUpdate();
      });

      this.entitySubscriptions.set(key, subscription);
    });
  }

  private getSources(): PriceLabelSource[] {
    const sources: PriceLabelSource[] = [];

    if (this.mainSeries) {
      sources.push({
        id: 'main',
        role: 'main',
        series: this.mainSeries,
        collisionGroup: 'main',
        priority: SOURCE_PRIORITY.main,
      });
    }

    this.compareEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('compare', entity));
    });

    this.indicatorEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('indicator', entity));
    });

    return sources;
  }

  private getEntitySources(collection: EntityCollection, entity: Indicator): PriceLabelSource[] {
    const isVolume = collection === 'indicator' && entity.getType() === IndicatorsIds.Volume;

    const role: SourceRole = collection === 'compare' ? 'compare' : isVolume ? 'volume' : 'indicator';

    const collisionGroup =
      role === 'volume' ? 'volume' : role === 'compare' ? `compare:${entity.getId()}` : `indicator:${entity.getId()}`;

    return Array.from(entity.getSeriesMap().entries()).map(([seriesId, series]) => ({
      id: `${collection}:${entity.getId()}:${seriesId}`,
      role,
      series,
      collisionGroup,
      priority: SOURCE_PRIORITY[role],
    }));
  }

  private ensureSourceDefaults(series: SeriesStrategies): SourceDefaults {
    const currentDefaults = this.sourceDefaults.get(series);

    if (currentDefaults) {
      return currentDefaults;
    }

    const options = series.options();

    const defaults: SourceDefaults = {
      lastValueVisible: options.lastValueVisible,
      priceLineVisible: options.priceLineVisible,
      title: options.title ?? '',
    };

    this.sourceDefaults.set(series, defaults);

    return defaults;
  }

  private restoreSourceOptions(series: SeriesStrategies): void {
    const defaults = this.sourceDefaults.get(series);

    if (!defaults) {
      return;
    }

    try {
      series.applyOptions(defaults);
    } catch {
      // Серия могла быть удалена раньше контроллера.
    }
  }

  private applyDisplayMode(): void {
    this.applyDisplayModeToSources(this.getSources());

    if (!this.isHistoryMode) {
      this.hideCurrentPriceLine();
    }
  }

  private applyDisplayModeToSources(sources: readonly PriceLabelSource[]): void {
    sources.forEach((source) => {
      const defaults = this.ensureSourceDefaults(source.series);

      try {
        if (source.role === 'volume') {
          source.series.applyOptions({
            lastValueVisible: false,
            priceLineVisible: false,
            title: '',
          });

          return;
        }

        const normalTitle = source.role === 'main' ? this.mainSymbol : defaults.title;

        source.series.applyOptions({
          lastValueVisible: this.isHistoryMode ? false : defaults.lastValueVisible,
          title: this.isHistoryMode ? '' : normalTitle,
        });
      } catch {
        // Серия могла быть удалена раньше контроллера.
      }
    });
  }

  private getHistoryMode(logicalRange: LogicalRange | null): boolean {
    if (!logicalRange || !this.mainSeries) {
      return false;
    }

    const barsInfo = this.mainSeries.barsInLogicalRange(logicalRange);

    return (barsInfo?.barsAfter ?? 0) > 0;
  }

  private refreshHistoryMode(): void {
    const nextHistoryMode = this.getHistoryMode(this.visibleLogicalRange);

    if (this.isHistoryMode === nextHistoryMode) {
      return;
    }

    this.isHistoryMode = nextHistoryMode;

    this.applyDisplayMode();
  }

  private scheduleUpdate(): void {
    if (this.updateFrame !== null) {
      return;
    }

    if (typeof requestAnimationFrame !== 'function') {
      this.update();

      return;
    }

    this.updateFrame = requestAnimationFrame(() => {
      this.updateFrame = null;
      this.update();
    });
  }

  private update(): void {
    const sources = this.getSources();
    const groups = this.collectAxisGroups(sources);

    this.updateCurrentPriceLine(sources);
    this.resolveRealtimeLabelCollisions(groups, sources);
    this.updateAxisLayers(groups, sources);
  }

  private collectAxisGroups(sources: readonly PriceLabelSource[]): Map<string, AxisLabelsGroup> {
    const groups = new Map<string, AxisLabelsGroup>();

    sources.forEach((source) => {
      if (!source.series.isVisible()) {
        return;
      }

      if (source.role !== 'volume' && !this.isHistoryMode) {
        return;
      }

      const label = this.createLabel(source);

      if (!label) {
        return;
      }

      const paneIndex = source.series.getPane().paneIndex();

      const side = getAxisSide(source);
      const axisKey = getAxisKey(paneIndex, side);

      const group = groups.get(axisKey);

      if (group) {
        group.labels.push(label);

        return;
      }

      groups.set(axisKey, {
        paneIndex,
        side,
        labels: [label],
      });
    });

    return groups;
  }

  private resolveRealtimeLabelCollisions(
    groups: Map<string, AxisLabelsGroup>,
    sources: readonly PriceLabelSource[],
  ): void {
    const mainSource = sources.find((source) => source.role === 'main');

    if (!mainSource || !mainSource.series.isVisible()) {
      return;
    }

    const defaults = this.ensureSourceDefaults(mainSource.series);

    if (!this.isHistoryMode && !defaults.lastValueVisible) {
      return;
    }

    const currentCoordinate = this.getCurrentMainPriceCoordinate();

    if (currentCoordinate === null) {
      return;
    }

    const paneIndex = mainSource.series.getPane().paneIndex();

    const side = getAxisSide(mainSource);

    const group = groups.get(getAxisKey(paneIndex, side));

    if (!group) {
      return;
    }

    group.labels = stackLabelsAboveReservedLabel(group.labels, currentCoordinate);
  }

  private createLabel(source: PriceLabelSource): PriceAxisLabel | null {
    const data = this.getSourceData(source);

    const price = getDataPrice(data);

    if (price === null) {
      return null;
    }

    const coordinate = source.series.priceToCoordinate(price);

    if (coordinate === null) {
      return null;
    }

    const text = source.role === 'volume' ? formatCompactNumber(price) : this.formatValue(source.series, price);

    return {
      id: source.id,
      collisionGroup: source.collisionGroup,
      desiredCoordinate: coordinate,
      text,
      color: getSeriesColor(source.series, data),
      style: this.isHistoryMode ? 'outlined' : 'filled',
      priority: source.priority,
      height: PRICE_AXIS_LABEL_HEIGHT,
    };
  }

  private getSourceData(source: PriceLabelSource): unknown {
    if (this.isHistoryMode && this.visibleLogicalRange) {
      return source.series.dataByIndex(Math.floor(this.visibleLogicalRange.to), MismatchDirection.NearestLeft);
    }

    const data = source.series.data();

    return data.length > 0 ? data[data.length - 1] : null;
  }

  private updateAxisLayers(groups: Map<string, AxisLabelsGroup>, sources: readonly PriceLabelSource[]): void {
    const activeLayerKeys = new Set<string>();

    groups.forEach((group, axisKey) => {
      const host = this.getAxisHost(group.paneIndex, group.side, sources);

      if (!host) {
        return;
      }

      activeLayerKeys.add(axisKey);

      this.getOrCreateLayer(axisKey, host).primitive.setLabels(group.labels);
    });

    this.layers.forEach((layer, axisKey) => {
      if (activeLayerKeys.has(axisKey)) {
        return;
      }

      try {
        layer.host.detachPrimitive(layer.primitive);
      } catch {
        // Серия могла быть удалена раньше контроллера.
      }

      this.layers.delete(axisKey);
    });
  }

  private getAxisHost(
    paneIndex: number,
    side: PriceAxisSide,
    sources: readonly PriceLabelSource[],
  ): SeriesStrategies | null {
    if (paneIndex === MAIN_PANE_INDEX && side === Direction.Right && this.mainSeries) {
      return this.mainSeries;
    }

    const regularSource = sources.find(
      (source) =>
        source.role !== 'volume' && source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side,
    );

    if (regularSource) {
      return regularSource.series;
    }

    const fallbackSource = sources.find(
      (source) => source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side,
    );

    return fallbackSource?.series ?? null;
  }

  private getOrCreateLayer(axisKey: string, host: SeriesStrategies): AxisLayer {
    const currentLayer = this.layers.get(axisKey);

    if (currentLayer?.host === host) {
      return currentLayer;
    }

    if (currentLayer) {
      try {
        currentLayer.host.detachPrimitive(currentLayer.primitive);
      } catch {
        // Серия могла быть удалена раньше контроллера.
      }
    }

    const primitive = new PriceAxisLabelsPrimitive();

    host.attachPrimitive(primitive);

    const nextLayer: AxisLayer = {
      host,
      primitive,
    };

    this.layers.set(axisKey, nextLayer);

    return nextLayer;
  }

  private updateCurrentPriceLine(sources: readonly PriceLabelSource[]): void {
    const mainSource = sources.find((source) => source.role === 'main');

    if (!this.isHistoryMode || !mainSource || !mainSource.series.isVisible()) {
      this.hideCurrentPriceLine();

      return;
    }

    const data = mainSource.series.data();

    const lastData = data.length > 0 ? data[data.length - 1] : null;

    const price = getDataPrice(lastData);

    if (price === null) {
      this.hideCurrentPriceLine();

      return;
    }

    const color = getSeriesColor(mainSource.series, lastData);

    const priceLine = this.getCurrentPriceLine(mainSource.series, color);

    priceLine.applyOptions({
      price,
      color,
      lineVisible: false,
      axisLabelVisible: true,
      axisLabelColor: color,
      axisLabelTextColor: getContrastTextColor(color),
      title: this.mainSymbol,
    });
  }

  private getCurrentMainPriceCoordinate(): number | null {
    if (!this.mainSeries) {
      return null;
    }

    const data = this.mainSeries.data();

    const lastData = data.length > 0 ? data[data.length - 1] : null;

    const price = getDataPrice(lastData);

    return price === null ? null : this.mainSeries.priceToCoordinate(price);
  }

  private getCurrentPriceLine(series: SeriesStrategies, color: string): IPriceLine {
    if (this.currentPriceLine && this.currentPriceLineHost === series) {
      return this.currentPriceLine;
    }

    this.removeCurrentPriceLine();

    this.currentPriceLine = series.createPriceLine({
      price: 0,
      color,
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });

    this.currentPriceLineHost = series;

    return this.currentPriceLine;
  }

  private hideCurrentPriceLine(): void {
    this.currentPriceLine?.applyOptions({
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });
  }

  private removeCurrentPriceLine(): void {
    if (this.currentPriceLine && this.currentPriceLineHost) {
      try {
        this.currentPriceLineHost.removePriceLine(this.currentPriceLine);
      } catch {
        // Серия могла быть удалена раньше контроллера.
      }
    }

    this.currentPriceLine = null;
    this.currentPriceLineHost = null;
  }

  private formatValue(series: SeriesStrategies, price: number): string {
    const { mode } = series.priceScale().options();

    if (mode !== PriceScaleMode.Percentage && mode !== PriceScaleMode.IndexedTo100) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

    const logicalRange = this.visibleLogicalRange;

    if (!logicalRange) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

    const firstVisibleData = series.dataByIndex(Math.ceil(logicalRange.from), MismatchDirection.NearestRight);

    const firstVisiblePrice = getDataPrice(firstVisibleData);

    if (firstVisiblePrice === null || firstVisiblePrice === 0) {
      return formatPrice(price) ?? series.priceFormatter().format(price);
    }

    if (mode === PriceScaleMode.Percentage) {
      const percentage = ((price - firstVisiblePrice) / firstVisiblePrice) * 100;

      return formatPercent(percentage);
    }

    const indexedValue = (price / firstVisiblePrice) * 100;

    return formatPrice(indexedValue) ?? indexedValue.toString();
  }
}