import { _decorator, Color, Component, Enum, Node, Sprite, tween, Vec3 } from 'cc';
import { CupHeight, WaterColorHex, WaterColors } from '../TakeGobletGlobalInstance';
import { Water } from './Water';
import { EventDispatcher } from 'db://assets/core_tgx/easy_ui_framework/EventDispatcher';
import { GameEvent } from '../Enum/GameEvent';
const { ccclass, property, executeInEditMode } = _decorator;

/** 调酒杯组件脚本*/
@ccclass('CocktailCup')
@executeInEditMode
export class CocktailCup extends Component {

    @property(Sprite)
    sprite: Sprite = null!

    @property({ type: Enum(CupHeight), displayName: '杯高度' })
    cupHeight: CupHeight = CupHeight.Two

    @property({ type: Enum(WaterColors) })
    private _cupColor: WaterColors = WaterColors.Blue

    @property({ type: Enum(WaterColors) })
    get cupColor() {
        return this._cupColor
    }
    set cupColor(value) {
        this._cupColor = value
        this.changeColor()
    }

    @property(Node)
    waters: Node = null!;  //水节点

    currentLayers: number = 0;

    onLoad() {
        // 初始化时隐藏所有水层
        this.waters.children.forEach(water => water.active = false);
    }

    changeColor() {
        if (!this.sprite) return
        this.sprite.color = new Color(WaterColorHex[this._cupColor])
    }

    // 添加水层
    addLayer(color: WaterColors) {
        const nextIndex = this.waters.children.filter(n => n.active).length;
        const waterNode = this.waters.children[nextIndex];
        if (waterNode) {
            const water = waterNode.getComponent(Water)!;
            water.color = color;
            waterNode.active = true;

            // 添加后检查是否满杯
            this.checkAndDestroy();
        }
    }

    // 清空水层（消除时调用）
    reset() {
        this.waters.children.forEach(water => water.active = false);
        this.currentLayers = 0;
    }

    get isFull(): boolean {
        return this.waters.children.every(node => node.active);
    }

    checkAndDestroy() {
        if (this.isFull) {
            tween(this.node)
                .to(0.3, { scale: Vec3.ZERO })
                .call(() => {
                    this.node.destroy();
                    EventDispatcher.instance.emit(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.node);
                })
                .start();
        }
    }

    public get currentColor(): WaterColors {
        return this.cupColor;
    }

    public get remainingCapacity(): number {
        return this.cupHeight - this.waters.children.filter(n => n.active).length;
    }
}


