
const { ccclass, property } = cc._decorator;

@ccclass
export default class Main extends cc.Component {
    private _bg: cc.Sprite = null;
    private _x: number = 0;
    private _y: number = 0;
    private _z: number = 0;
    private _count = 0;
    private _isShake = false;
    
    protected onLoad(): void {

        // this.onSkew();
    }


    private onSkew() {
        this._bg = this.node.getComponentInChildren(cc.Sprite);

        function createBottleSpinAnimation(node) {
            cc.resources.loadDir("Anim_MB", cc.SpriteFrame, (err, spriteFrames) => {
                if (err) {
                    console.error("Lỗi load ảnh:", err);
                    return;
                }

                let clip = cc.AnimationClip.createWithSpriteFrames(spriteFrames, spriteFrames.length);
                console.log('spriteFrames.length', spriteFrames.length)
                clip.name = "bottleSpin";
                clip.wrapMode = cc.WrapMode.Loop; // Lặp vô hạn
                clip.speed = 1; // Tốc độ chạy animation (1 giây/lượt)

                let animation = node.getComponent(cc.Animation) || node.addComponent(cc.Animation);
                animation.addClip(clip);
                animation.play("bottleSpin");
            });
        }

        createBottleSpinAnimation(this._bg.node);
    }

    protected start(): void {
        this.scheduleOnce(() => {
            this.testDevice();
        }, 2)
    }



    private testDevice() {
        window.addEventListener("devicemotion", (event) => {
            if (!event.accelerationIncludingGravity) {
                return;
            }

            const x = event.accelerationIncludingGravity.x;
            const y = event.accelerationIncludingGravity.y;
            const z = event.accelerationIncludingGravity.z;

            if (x - this._x > 5 || y - this._y > 5 || z - this._z > 5) {
                if (this._isShake) {
                    this._count++;
                }
            }

            if (x - this._x < -5 || y - this._y < -5 || z - this._z < -5) {
                if (!this._isShake) {
                    this._count++;
                }
            }

            if (this._count > 0) {
                this.scheduleOnce(() => {
                    this._count = 0;
                }, 1.5)
            }

            if (this._count > 5) {
                this._count = 0;
                cc.tween(this._bg.node)
                    .to(0.2, { position: cc.v3(20, 0, 0) })
                    .to(0.2, { position: cc.v3(-20, 0, 0) })
                    .to(0.2, { position: cc.v3(20, 0, 0) })
                    .to(0.2, { position: cc.v3(-20, 0, 0) })
                    .to(0.2, { position: cc.v3(0, 0, 0) })
                    .start();
            }


            this._x = x;
            this._y = y;
            this._z = z;
        });
    }

}
