import { roundToDecimalPlaces } from './ui_utils'

export default class Color {
  constructor(r = 0, g = 0, b = 0, a = 1) {
    this.R = r
    this.G = g
    this.B = b
    this.A = a
  }

  rgbToHex() {
    const r = this.R
    const g = this.G
    const b = this.B
    const hexString = ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1).toUpperCase()
    return `#${hexString}`;
  }

  hexToRgb(hexColor) {
    const hex = hexColor.slice(1); // 去除 "#" 符号
    const bigint = parseInt(hex, 16);
    const R = (bigint >> 16) & 255;
    const G = (bigint >> 8) & 255;
    const B = bigint & 255;
    return {
      R,
      G,
      B
    }
  }

  getColor() {
    return `rgba(${this.R}, ${this.G}, ${this.B}, ${this.A})`
  }

  setColor(r, g, b) {
    this.R = r
    this.G = g
    this.B = b
  }

  formatColor(value) {
    const format = this.getColorFormat(value)
    if (format === 'hex') {
      const { R, G, B } = this.hexToRgb(value)
      return {
        R,
        G,
        B
      }
    } else if (format === 'rgb') {
      const match = value.match(/(\d+),\s*(\d+),\s*(\d+)/)
      const R = parseInt(match[1])
      const G = parseInt(match[2])
      const B = parseInt(match[3])
      return {
        R,
        G,
        B
      }
    } else {
      console.error({
        message: 'Invalid color value'
      })
    }
  }

  getColorFormat(colorString) {
    if (colorString.startsWith("#")) {
      return "hex";
    } else if (colorString.startsWith("rgb(")) {
      return "rgb";
    } else {
      return "unknown";
    }
  }

  convertColorToCppFormat() {
    const R = roundToDecimalPlaces(this.R / 255)
    const G = roundToDecimalPlaces(this.G / 255)
    const B = roundToDecimalPlaces(this.B / 255)
    return {
      R,
      G,
      B
    }
  }
}
