import { _decorator, Component, instantiate, lerp, Node, Prefab } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('Wall')
export class Wall extends Component {

    @property(Node) top: Node = null;

    @property(Node) bottom: Node = null;

    @property isInit = false;

    @property(Prefab) lightPrefab: Prefab = null;
    @property(Prefab) ringPrefab: Prefab = null;

    dH: number = 1;

    onLoad() {
        if (!this.isInit) {
            this.reset();
        }
    }

    get topY() {
        return this.top.position.y + this.node.position.y;
    }

    reset() {
        this.dH = Math.random() * 3 + 2;
        this.top.setPosition(0, this.dH / 2, 0);
        this.bottom.setPosition(0, -this.dH / 2, 0);

        this.light?.destroy();
        this.ring?.destroy();
    }

    resetGuide() {
        this.dH = Math.random() * 0.5 + 4.5;
        this.top.setPosition(0, this.dH / 2, 0);
        this.bottom.setPosition(0, -this.dH / 2, 0);
    }

    resetDeath() {
        this.dH = Math.random() * 3 + 0.5;
        this.top.setPosition(0, this.dH / 2, 0);
        this.bottom.setPosition(0, -this.dH / 2, 0);
    }

    light: Node = null;

    createLight() {
        this.light = instantiate(this.lightPrefab);
        this.node.addChild(this.light);
        this.light.setScale(1, this.dH, 1);
    }

    ring: Node = null;

    createRing(scale = lerp(this.dH * 0.4, this.dH * 0.75, Math.random())) {
        this.ring = instantiate(this.ringPrefab);
        this.node.addChild(this.ring);

        this.ring.setScale(scale, scale);

        const dyHalf = (this.dH - scale) / 2;
        const y = lerp(-dyHalf, dyHalf, Math.random());
        this.ring.setPosition(0, y);
    }
}

