import { eventTarget, CHECK_TOUCH, CHECK_FRAGMENT, HAMMER, RESET_FRAGMENT, PLAY_DROP_SOUND, DROP_ALL_FRAGMENT } from "../Events";


const { ccclass, property } = cc._decorator;

@ccclass
export default class FragmentController extends cc.Component {

    private _collider: cc.PolygonCollider = null;
    private _physicsCollider: cc.PhysicsPolygonCollider = null;
    private _rg: cc.RigidBody = null;
    private _siblingIndex: number = 0;
    private _isDropped: boolean = false;

    onLoad() {
        this._collider = this.node.getComponent(cc.PolygonCollider);
        this._physicsCollider = this.node.getComponent(cc.PhysicsPolygonCollider);
        this._physicsCollider.points = this._collider.points;
        this._rg = this.node.getComponent(cc.RigidBody);
        this._siblingIndex = this.node.getSiblingIndex();
        this.reset();

        eventTarget.on(CHECK_TOUCH, this.checkTouch, this);
        eventTarget.on(RESET_FRAGMENT, this.reset, this);
        eventTarget.on(DROP_ALL_FRAGMENT, () => this.node.name.includes('nap') && this.dropFragment(), this);
    }

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

    private checkTouch(point: cc.Vec2) {
        if (this._isDropped) {
            return;
        }
        const pos = point.clone().subtract(cc.v2(this.node.position.x, this.node.position.y));

        let isInside = cc.Intersection.pointInPolygon(pos, this._collider.points);
        if (isInside) {
            eventTarget.emit(HAMMER, point);
            this.dropFragment();
        }
    }

    private dropFragment() {
        this._isDropped = true;
        const pos = this.node.position;
        this.node.setSiblingIndex(-1);
        eventTarget.emit(CHECK_FRAGMENT, this.node.name);

        cc.tween(this.node)
            .delay(0.5)
            .call(() => {
                eventTarget.emit(PLAY_DROP_SOUND);
            })
            .to(0.1, { scale: 0.9 })
            .to(0.1, { scale: 1.05 })
            .to(0.2, { position: pos.clone().multiplyScalar(1.2) })
            .call(() => {
                this._physicsCollider.enabled = true;
                this._rg.type = cc.RigidBodyType.Dynamic;
                this._rg.gravityScale = 10;
            })
            .delay(1)
            .to(0, { scale: 1 })
            .start();
    }
}
