import { eventTarget, CHECK_TOUCH, CHECK_FRAGMENT, HAMMER, RESET_FRAGMENT, PLAY_DROP_SOUND } 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;

    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);
    }

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

    private checkTouch(point: cc.Vec2) {
        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() {
        const pos = this.node.position;
        this.node.setSiblingIndex(-1);
        cc.tween(this.node)
            .delay(0.5)
            .call(() => {
                eventTarget.emit(PLAY_DROP_SOUND);
            })
            .to(0.2, { scale: 0.95 })
            .to(0.2, { scale: 1.05, position: pos.clone().multiplyScalar(1.2) })
            .call(() => {
                this._physicsCollider.enabled = true;
                this._rg.type = cc.RigidBodyType.Dynamic;
                this._rg.gravityScale = 5;
            })
            .delay(1)
            .call(() => {
                eventTarget.emit(CHECK_FRAGMENT, this.node.name);
            })
            .start();
    }
}
