import { Color, ColorRepresentation } from "three";

import { Mathf } from "../../engine/engine_math.js";

/**
 * RGBAColor is a class that represents a color with red, green, blue and alpha components.
 */
export class RGBAColor extends Color {
    alpha: number = 1;

    get isRGBAColor() { return true; }

    set a(val: number) { this.alpha = val; }
    get a() { return this.alpha; }

    constructor(color: ColorRepresentation);
    /**
     * Creates a new RGBAColor with the given red, green, blue and alpha components.   
     * Color values should be in the range [0, 1].
     */
    constructor(r: number, g: number, b: number, a: number);
    constructor(r: number | ColorRepresentation, g?: number, b?: number, a?: number) {
        // if the user passed in the r, g, b, a components
        if (g != undefined && b != undefined) {
            super(r as number, g, b);
            this.alpha = a as number;
        }
        // if the user passed in a color representation
        else {
            super(r);
            this.alpha = 1;
        }
    }

    clone(): this {
        const cloned = super.clone();
        cloned.alpha = this.alpha;
        return cloned;
    }

    copy(col: RGBAColor | Color) {
        this.r = col.r;
        this.g = col.g;
        this.b = col.b;

        if ("alpha" in col && typeof col.alpha === "number") {
            this.alpha = col.alpha;
        }
        else if (typeof col["a"] === "number") this.alpha = col["a"];
        return this;
    }

    lerp(color: Color, alpha: number): this {
        const rgba = color as RGBAColor;
        if (rgba.alpha != undefined) this.alpha = Mathf.lerp(this.alpha, rgba.alpha, alpha);
        return super.lerp(color, alpha);
    }

    lerpColors(color1: Color, color2: Color, alpha: number): this {
        const rgba1 = color1 as RGBAColor;
        const rgba2 = color2 as RGBAColor;
        if (rgba1.alpha != undefined && rgba2.alpha != undefined) this.alpha = Mathf.lerp(rgba1.alpha, rgba2.alpha, alpha);
        return super.lerpColors(color1, color2, alpha);
    }

    multiply(color: Color): this {
        const rgba = color as RGBAColor;
        if (rgba.alpha != undefined) this.alpha = this.alpha * rgba.alpha;
        return super.multiply(color);
    }

    fromArray(array: number[], offset: number = 0): this {
        this.alpha = array[offset + 3];
        return super.fromArray(array, offset);
    }
}