import type { DateMemo, ChartOption, SplitData } from '../types/index.ts';

export class DateMemoHandler {
  private dateMemos: DateMemo[];
  private memoVisible: boolean = true;
  
  constructor(dateMemos: DateMemo[]) {
    this.dateMemos = dateMemos;
  }

  public addDateMemoMarkers(option: ChartOption, splitData: SplitData): ChartOption {
    const memoMarkers = this.dateMemos
      .map(memo => {
        const index = splitData.categoryData.indexOf(memo.日期);
        
        if (index !== -1) {
          return {
            value: [index, splitData.values[index].value[1]],
            symbol: 'rect',
            symbolSize: [20, 40],
            label: {
              show: this.memoVisible,
              position: 'top',
              formatter: memo.提示.split('').join('\n'),
              color: 'red',
              backgroundColor: 'yellow',
              padding: 4,
              borderRadius: 2,
              fontWeight: 'bold'
            },
            itemStyle: {
              color: 'transparent'
            }
          };
        }
        return null;
      })
      .filter(item => item !== null);

    const existingSeriesIndex = option.series.findIndex(
      series => series.name === 'DateMemo'
    );

    if (existingSeriesIndex !== -1) {
      option.series[existingSeriesIndex].data = memoMarkers;
    } else {
      option.series.push({
        name: 'DateMemo',
        type: 'scatter',
        data: memoMarkers,
        tooltip: {
          show: false
        }
      } as any);
    }

    return option;
  }

  public toggleMemoVisibility(visible: boolean): void {
    this.memoVisible = visible;
  }

  public updateMemoVisibility(option: ChartOption): void {
    const dateMemoSeries = option.series.find(
      series => series.name === 'DateMemo'
    );

    if (dateMemoSeries && dateMemoSeries.data) {
      dateMemoSeries.data.forEach((item: any) => {
        if (item && item.label) {
          item.label.show = this.memoVisible;
        }
      });
    }
  }
} 