import type { StockData, ProcessedData, SplitData } from '../../types/index';
import { CHART_COLORS } from '../constants/colors';

export class DataProcessor {
  private readonly upFillColor = CHART_COLORS.UP_FILL;
  private readonly upColor = CHART_COLORS.UP;
  private readonly downColor = CHART_COLORS.DOWN;
  private readonly limitUpColor = CHART_COLORS.LIMIT_UP;
  private readonly limitDownColor = CHART_COLORS.LIMIT_DOWN;

  processData(data: StockData[]): ProcessedData[] {
    return data.map(item => this.processStockItem(item));
  }

  splitData(processedData: ProcessedData[]): SplitData {
    const categoryData: string[] = [];
    const values: any[] = [];
    const volumes: [number, string, number][] = [];

    processedData.forEach((item, i) => {
      categoryData.push(item.categoryData);
      values.push(item.values);

      const open = Number(item.values.value[0]);
      const close = Number(item.values.value[1]);
      const zd = Number(item.values.value[4]);
      const direction = (zd < 0 || open > close) ? -1 : 1;

      volumes.push([i, item.volumes, direction]);
    });

    return { categoryData, values, volumes };
  }

  private processStockItem(item: StockData): ProcessedData {
    const open = Number(item.o);
    const close = Number(item.c);
    const zd = Number(item.zd);
    const isDown = zd < 0 || open > close;
    const isLimitUp = zd > 9.7;
    const isLimitDown = zd < -9.7;

    return {
      categoryData: item.d,
      values: {
        value: [item.o, item.c, item.l, item.h, item.pc || item.zd],
        itemStyle: {
          color: this.getItemColor(isDown, isLimitUp, isLimitDown),
          borderColor: this.getBorderColor(isDown, isLimitUp, isLimitDown)
        }
      },
      volumes: item.v
    };
  }

  private getItemColor(isDown: boolean, isLimitUp: boolean, isLimitDown: boolean): string {
    if (isLimitUp) return this.limitUpColor;
    if (isLimitDown) return this.limitDownColor;
    return isDown ? this.downColor : this.upColor;
  }

  private getBorderColor(isDown: boolean, isLimitUp: boolean, isLimitDown: boolean): string {
    if (isLimitUp) return this.limitUpColor;
    if (isLimitDown) return this.limitDownColor;
    return isDown ? this.downColor : this.upColor;
  }
} 