import { eventTarget, RESET_FRAGMENT, SHAKE_FRAGMENT } from "../Events";


const { ccclass, property } = cc._decorator;

@ccclass
export default class BehindFragment extends cc.Component {
    private _rg: cc.RigidBody = null;
    private _physicsCollider: cc.PhysicsCollider = null;
    private _isDropped: boolean = false;

    onLoad() {
        this._rg = this.node.getComponent(cc.RigidBody);
        this._rg.type = cc.RigidBodyType.Static;
        this._physicsCollider = this.node.getComponent(cc.PhysicsCollider);
        this._physicsCollider.enabled = false;

        eventTarget.on(RESET_FRAGMENT, this.reset, this);
        eventTarget.on(SHAKE_FRAGMENT, this.shakeFragment, this);
    }
    
    public shakeFragment() {
        if (this._isDropped) {
            return;
        }

        cc.tween(this.node)
            .repeat(2, cc.tween(this.node)
                .by(0.05, { position: cc.v3(-10, -10) })
                .by(0.05, { position: cc.v3(10, 10) })
            )
            .start();
    }

    public onDrop() {
        this._isDropped = true;
        const position = cc.v3(Math.random() * 100 - 50, Math.random() * 100);
        cc.tween(this.node)
            .by(1, { position })
            .call(() => {
                this._rg.type = cc.RigidBodyType.Dynamic;
                this._rg.gravityScale = 10;
                this._physicsCollider.enabled = true;
            })
            .start();
    }

    public reset() {
        this._physicsCollider.enabled = false;
        this._rg.type = cc.RigidBodyType.Static;
        this.node.angle = 0;
    }
}
