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


import dayjs from 'dayjs';
import {
  ColorType,
  createChart,
  createSeriesMarkers,
  CrosshairMode,
  type IChartApi,
  type ISeriesApi,
  type ISeriesMarkersPluginApi,
  LineSeries,
  LineStyle,
  type MouseEventParams,
  PriceScaleMode,
  type Time,
} from 'lightweight-charts';
import { BehaviorSubject } from 'rxjs';

import { createInitialSeasonalityState, DEFAULT_SEASONALITY_YEARS } from '@src/constants';
import { ZIndex } from '@src/core/ContainerManager';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { getThemeStore } from '@src/theme/store';
import { getLocale, t } from '@src/translations';
import { SeasonalityViewType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import {
  buildSeasonality,
  buildSeasonalityTable,
  canvasToBlob,
  drawTextLayer,
  formatCompactNumber,
  formatPercent,
  getPercentPrecisionStep,
  getPricePrecisionStep,
  normalizeRange,
  toSeriesData,
} from '@src/utils';

import type { DataSourceParams } from '@src/core/DataSource';
import type {
  Candle,
  DailyClose,
  SeasonalityRange,
  SeasonalityScale,
  SeasonalityTableRow,
  SeasonalityYear,
} from '@src/types';

interface SeasonalityManagerParams {
  container: HTMLElement;
  getData: DataSourceParams['getData'];
}

interface SeasonalityPlot {
  year: SeasonalityYear;
  series: ISeriesApi<'Line'>;
  legend: HTMLSpanElement;
  legendValue: HTMLSpanElement;
  markers?: ISeriesMarkersPluginApi<Time>;
}

export class SeasonalityManager {
  private readonly currentYear = dayjs().year();
  private readonly state = new BehaviorSubject(createInitialSeasonalityState());
  private readonly chartContainer: HTMLDivElement;
  private readonly legend: HTMLDivElement;
  private readonly statusElement: HTMLDivElement;
  private readonly plots = new Map<number, SeasonalityPlot>();

  private chart: IChartApi | null = null;
  private allYears: SeasonalityYear[] = [];
  private tableRows: SeasonalityTableRow[] = [];
  private requestId = 0;
  private renderFrame: number | null = null;
  private destroyed = false;

  constructor(private readonly params: SeasonalityManagerParams) {
    const { chartContainer, legend, statusElement } = createSeasonalityElements(params.container);

    this.chartContainer = chartContainer;
    this.legend = legend;
    this.statusElement = statusElement;

    this.updateTheme();
  }

  public getState() {
    return this.state.asObservable();
  }

  public async show(symbolId: string, range?: SeasonalityRange): Promise<void> {
    if (this.destroyed || this.reuseHistory(symbolId, range)) {
      return;
    }

    const requestId = ++this.requestId;

    this.reset();

    this.showStatus(t('Loading seasonality'));

    this.state.next({
      ...this.state.value,
      symbolId,
      status: 'loading',
      tableRows: [],
      error: null,
    });

    try {
      if (!symbolId) {
        throw new Error('Select an instrument');
      }

      const rows = await this.loadHistory(symbolId, requestId);

      if (!this.isCurrent(requestId)) {
        return;
      }

      this.allYears = buildSeasonality(rows);
      this.tableRows = buildSeasonalityTable(this.allYears);
      this.setInitialRange(range);
    } catch (error) {
      if (!this.isCurrent(requestId)) {
        return;
      }

      this.reset();
      this.showStatus(t('Unable to load seasonality'));

      this.state.next({
        ...this.state.value,
        status: 'error',
        tableRows: [],
        error: String(error),
      });

      console.error('[Seasonality] History loading failed:', error);
    }
  }

  public setRange = (range: SeasonalityRange): void => {
    if (this.destroyed || this.allYears.length === 0) {
      return;
    }

    const state = this.state.value;
    const next = normalizeRange(range, state.minYear, state.maxYear);

    if (next.fromYear === state.fromYear && next.toYear === state.toYear) {
      return;
    }

    this.state.next({ ...state, ...next });

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

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

      if (!this.destroyed && this.allYears.length > 0) {
        this.renderRange();
      }
    });
  };

  public setDisplayMode = (displayMode: SeasonalityViewType): void => {
    if (this.destroyed || this.state.value.displayMode === displayMode) {
      return;
    }

    this.state.next({ ...this.state.value, displayMode });
  };

  public setScale = (scale: SeasonalityScale): void => {
    if (this.destroyed || this.state.value.scale === scale) {
      return;
    }

    this.state.next({ ...this.state.value, scale });

    if (!this.chart) {
      return;
    }

    this.plots.forEach((plot) => this.updateSeries(plot));

    this.fitCalendar();

    this.updateStatus();
    this.updateLegend();
  };

  public clear = (): void => {
    if (this.destroyed) {
      return;
    }

    this.requestId += 1;

    this.reset();

    this.state.next({
      ...this.state.value,
      status: 'idle',
      tableRows: [],
      error: null,
    });
  };

  public updateTheme(): void {
    const { colors } = getThemeStore();

    Object.assign(this.params.container.style, {
      backgroundColor: colors.chartBackground,
    });

    Object.assign(this.statusElement.style, {
      color: colors.chartTextPrimary,
    });

    this.legend.style.color = colors.chartTextPrimary;

    this.chart?.applyOptions(getThemeOptions());
  }

  public async copyImage(): Promise<void> {
    if (
      !this.chart ||
      this.state.value.status !== 'ready' ||
      this.state.value.displayMode !== SeasonalityViewType.Chart
    ) {
      return;
    }

    const canvas = this.chart.takeScreenshot(true, false);

    drawTextLayer(canvas, this.legend, this.chart.chartElement());

    const blob = await canvasToBlob(canvas);

    await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
  }

  public destroy(): void {
    if (this.destroyed) {
      return;
    }

    this.destroyed = true;
    this.requestId += 1;

    this.reset();

    this.chartContainer.remove();
    this.legend.remove();
    this.statusElement.remove();

    this.state.complete();
  }

  private isCurrent(requestId: number): boolean {
    return !this.destroyed && requestId === this.requestId;
  }

  private reuseHistory(symbolId: string, range?: SeasonalityRange): boolean {
    const state = this.state.value;

    if (state.symbolId !== symbolId) {
      return false;
    }

    if (state.status === 'loading') {
      return true;
    }

    if (this.allYears.length === 0) {
      return false;
    }

    if (range) {
      this.setRange(range);
    }

    return true;
  }

  private async loadHistory(symbolId: string, requestId: number): Promise<DailyClose[]> {
    const candles = new Map<number, Candle>();

    const loadPage = async (cursor?: Candle): Promise<void> => {
      if (!this.isCurrent(requestId)) {
        return;
      }

      const loaded = await this.params.getData(Timeframes['1d'], symbolId, cursor);

      if (!this.isCurrent(requestId) || !loaded?.length) {
        return;
      }

      const { oldest, newestTime } = mergeHistoryPage(loaded, candles);

      if (cursor && oldest.time >= cursor.time) {
        const isBoundaryOnly = oldest.time === cursor.time && newestTime === cursor.time;

        if (isBoundaryOnly) {
          return;
        }

        throw new Error(
          `History pagination made no progress: cursor=${cursor.time}, ` +
            `oldest=${oldest.time}, newest=${newestTime}, count=${loaded.length}`,
        );
      }

      return loadPage(oldest);
    };

    await loadPage();

    if (!this.isCurrent(requestId)) {
      return [];
    }

    return Array.from(candles.values(), (candle) => ({
      date: dayjs.unix(candle.time).format('YYYY-MM-DD'),
      close: candle.close,
    }));
  }

  private setInitialRange(range?: SeasonalityRange): void {
    if (this.allYears.length === 0) {
      this.showStatus(t('No seasonality data'));
      this.state.next({
        ...this.state.value,
        status: 'empty',
      });

      return;
    }

    const minYear = this.allYears[0].year;
    const maxYear = this.allYears[this.allYears.length - 1].year;

    const selected = normalizeRange(
      range ?? {
        fromYear: maxYear - DEFAULT_SEASONALITY_YEARS + 1,
        toYear: maxYear,
      },
      minYear,
      maxYear,
    );

    this.state.next({
      ...this.state.value,
      ...selected,
      minYear,
      maxYear,
    });

    this.renderRange();
  }

  private createChart(): IChartApi {
    const chart = createChart(this.chartContainer, {
      ...getThemeOptions(),
      autoSize: true,
      handleScroll: false,
      handleScale: false,
      kineticScroll: {
        mouse: false,
        touch: false,
      },
      rightPriceScale: {
        mode: PriceScaleMode.Normal,
        autoScale: true,
        alignLabels: true,
        visible: true,
        borderVisible: false,
      },
      leftPriceScale: {
        visible: false,
      },
      timeScale: {
        timeVisible: false,
        secondsVisible: false,
        borderVisible: false,
        allowBoldLabels: false,
        rightOffset: 0,
        tickMarkFormatter: formatSeasonDate,
        lockVisibleTimeRangeOnResize: true,
      },
      localization: {
        locale: getLocale(),
        timeFormatter: formatSeasonDate,
      },
    });

    chart.subscribeCrosshairMove(this.onCrosshairMove);

    this.chart = chart;

    return chart;
  }

  private renderRange(): void {
    const chart = this.chart ?? this.createChart();
    const { fromYear, toYear } = this.state.value;

    const years = this.allYears.filter((year) => year.year >= fromYear && year.year <= toYear);

    this.plots.forEach((plot, year) => {
      if (year < fromYear || year > toYear) {
        plot.markers?.detach();
        chart.removeSeries(plot.series);
        this.plots.delete(year);
      }
    });

    const plots = years.map((year) => {
      const existing = this.plots.get(year.year);

      if (existing) {
        return existing;
      }

      const plot = this.createPlot(chart, year);

      this.plots.set(year.year, plot);

      return plot;
    });

    this.legend.replaceChildren(...plots.flatMap((plot) => [plot.legend, plot.legendValue]));

    if (plots.length > 0) {
      this.fitCalendar();
    }

    this.updateStatus();
    this.updateLegend();

    this.state.next({
      ...this.state.value,
      status: plots.length > 0 ? 'ready' : 'empty',
      tableRows: this.tableRows.filter((row) => row.year >= fromYear && row.year <= toYear),
    });
  }

  private fitCalendar(): void {
    this.chart?.timeScale().setVisibleRange({
      from: '2000-01-01',
      to: '2000-12-31',
    });
  }

  private createPlot(chart: IChartApi, year: SeasonalityYear): SeasonalityPlot {
    const color = getYearColor(year.year);
    const legend = document.createElement('span');
    const legendValue = document.createElement('span');

    legend.textContent = String(year.year);

    Object.assign(legendValue.style, {
      color,
      textAlign: 'right',
    });

    const plot: SeasonalityPlot = {
      year,
      legend,
      legendValue,
      series: chart.addSeries(LineSeries, {
        title: String(year.year),
        color,
        priceLineVisible: false,
        lastValueVisible: true,
        lineWidth: year.year === this.currentYear ? 3 : 1,
        pointMarkersVisible: false,
        crosshairMarkerVisible: true,
      }),
    };

    if (year.year === this.currentYear) {
      plot.markers = createSeriesMarkers(plot.series, [], {
        autoScale: false,
      });
    }

    this.updateSeries(plot);

    return plot;
  }

  private updateSeries({ series, year, markers }: SeasonalityPlot): void {
    const { scale } = this.state.value;
    const isPercentage = scale === PriceScaleMode.Percentage;

    series.applyOptions({
      priceFormat: {
        type: 'custom',
        minMove: isPercentage ? getPercentPrecisionStep() : getPricePrecisionStep(),
        formatter: (value: number) => (isPercentage ? formatPercent(value) : formatCompactNumber(value)),
      },
    });

    series.setData(toSeriesData(year, scale));

    if (markers) {
      const lastPoint = year.points[year.points.length - 1];
      const value = isPercentage ? lastPoint.percentage : lastPoint.price;

      markers.setMarkers(
        value === null
          ? []
          : [
              {
                time: lastPoint.chartDate,
                position: 'inBar',
                shape: 'circle',
                color: getYearColor(year.year),
                size: 1,
              },
            ],
      );
    }
  }

  private updateStatus(): void {
    if (this.plots.size === 0) {
      this.showStatus(t('No seasonality data'));

      return;
    }

    const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;

    const hasBaseline = Array.from(this.plots.values()).some((plot) => plot.year.baselinePrice > 0);

    if (isPercentage && !hasBaseline) {
      this.showStatus(t('Percentage requires a positive baseline'));

      return;
    }

    this.statusElement.style.display = 'none';
  }

  private onCrosshairMove = (event: MouseEventParams): void => {
    this.updateLegend(event);
  };

  private updateLegend(event?: MouseEventParams): void {
    const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;

    this.plots.forEach(({ year, series, legendValue }) => {
      const lastPoint = year.points[year.points.length - 1];

      let value = isPercentage ? lastPoint.percentage : lastPoint.price;

      if (event?.time !== undefined) {
        const point = event.seriesData.get(series);

        value = point && 'value' in point && typeof point.value === 'number' ? point.value : null;
      }

      legendValue.textContent = value === null ? '—' : series.priceFormatter().format(value);
    });
  }

  private showStatus(message: string): void {
    this.statusElement.textContent = message;
    this.statusElement.style.display = 'flex';
  }

  private reset(): void {
    if (this.renderFrame !== null) {
      cancelAnimationFrame(this.renderFrame);
      this.renderFrame = null;
    }

    this.chart?.unsubscribeCrosshairMove(this.onCrosshairMove);
    this.plots.forEach((plot) => plot.markers?.detach());
    this.chart?.remove();

    this.chart = null;
    this.allYears = [];
    this.tableRows = [];

    this.plots.clear();
    this.legend.replaceChildren();

    this.statusElement.style.display = 'none';
  }
}

function mergeHistoryPage(loaded: Candle[], candles: Map<number, Candle>): { oldest: Candle; newestTime: number } {
  let oldest = loaded[0];
  let oldestTime = Infinity;
  let newestTime = -Infinity;

  for (let index = loaded.length - 1; index >= 0; index -= 1) {
    const candle = loaded[index];

    if (!Number.isFinite(candle.time) || !Number.isFinite(candle.close)) {
      throw new Error('Invalid daily candle');
    }

    const time = Math.floor(candle.time > 1e10 ? candle.time / 1000 : candle.time);

    const normalized = time === candle.time ? candle : { ...candle, time };

    newestTime = Math.max(newestTime, time);

    if (time < oldestTime) {
      oldest = normalized;
      oldestTime = time;
    }

    if (!candles.has(time)) {
      candles.set(time, normalized);
    }
  }

  return { oldest, newestTime };
}

function getThemeOptions() {
  const { colors } = getThemeStore();

  return {
    layout: {
      background: {
        type: ColorType.Solid,
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
      panes: {
        separatorColor: colors.chartPaneSeparator,
        separatorHoverColor: colors.chartPaneSeparator,
        enableResize: false,
      },
    },

    grid: {
      vertLines: {
        color: colors.chartGridLine,
      },
      horzLines: {
        color: colors.chartGridLine,
      },
    },

    crosshair: {
      mode: CrosshairMode.Normal,
      vertLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: LineStyle.Solid,
      },
      horzLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: LineStyle.Dashed,
      },
    },
  };
}

function formatSeasonDate(time: Time): string {
  if (typeof time === 'object') {
    const day = String(time.day).padStart(2, '0');
    const month = String(time.month).padStart(2, '0');

    return `${day}.${month}`;
  }

  const date = typeof time === 'number' ? new Date(time * 1000).toISOString() : time;

  return `${date.slice(8, 10)}.${date.slice(5, 7)}`;
}

function getYearColor(year: number): string {
  return COMPARE_COLOR_PALETTE[year % COMPARE_COLOR_PALETTE.length];
}

function createSeasonalityElements(container: HTMLElement) {
  const chartContainer = document.createElement('div');
  const legend = document.createElement('div');
  const statusElement = document.createElement('div');

  Object.assign(chartContainer.style, {
    position: 'absolute',
    inset: 0,
  });

  Object.assign(legend.style, {
    width: 'max-content',
    position: 'absolute',
    top: 0,
    left: 0,
    display: 'grid',
    gridTemplateColumns: 'max-content max-content',
    justifyContent: 'start',
    alignItems: 'center',
    gap: 'var(--space-0125) var(--space-0500)',
    fontSize: 'var(--space-0750)',
    lineHeight: 'var(--space-1000)',
    fontVariantNumeric: 'tabular-nums',
    pointerEvents: 'none',
    zIndex: ZIndex.Legend,
  });

  Object.assign(statusElement.style, {
    position: 'absolute',
    inset: 0,
    display: 'none',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
    pointerEvents: 'none',
  });

  container.append(chartContainer, legend, statusElement);

  return { chartContainer, legend, statusElement };
}