import FF from "../FF";
import FSprite from "../object/FSprite";

/**
 * 触发机关关门
 */
const {ccclass, property} = cc._decorator;

@ccclass
export default class FCloseDoor extends cc.Component {

   /**
     * 伙伴初始化区域
     */
    @property({
        type:cc.Node,
        displayName: '摄像机移动的目标位置'
    })
    mCameraPos: cc.Node = null;
    /**
     * 控制的栅栏
     */
    @property([cc.Node])
    mFenceTrigger: Array<cc.Node> = [];

    private ff:FF;

    onBeginContact(contact: cc.PhysicsContact, selfCollider: cc.PhysicsCollider, otherCollider: cc.PhysicsCollider){
       
        if(otherCollider.node.group == 'A'){//主角踩到机关
            let obj = otherCollider.node.getComponent(FSprite);
            this.ff = obj.ff;
            if(obj == this.ff.mainSprite){
                this.node.removeComponent(cc.PhysicsBoxCollider);
                this.ff.pauseSprite(true)
                this.moveCamera(()=>{
                    cc.tween(this).sequence(
                        cc.delayTime(1),
                        cc.callFunc(()=>{
                            this.ff.pauseSprite(false)
                        })
                    ).start();
                    for (let i = 0; i < this.mFenceTrigger.length; i++) {
                        const element = this.mFenceTrigger[i];
                        element.active = true;
    
                        let nodes = element.children;
                        nodes.forEach(tmp => {
                            let spine = tmp.getComponent(sp.Skeleton);
                            if(spine){
                                spine.setAnimation(0, 'open', false);
                            }
                        });
                    }
                })
            }
        }
    }
    private moveCamera(finishCallback:()=>void){
        if(!this.mCameraPos){
            finishCallback();
            return;
        }
        let map = this.ff.mMap;
        let camera = map.mCamera;

        let pos = cc.v2();
        let winsize = cc.winSize;
        pos.x = this.node.x + this.mCameraPos.x-winsize.width/2;
        pos.y = this.node.y + this.mCameraPos.y-winsize.height/2;

        cc.tween(camera.node).sequence(
            cc.moveTo(1,pos),
            cc.callFunc(()=>{
                finishCallback();
            })
        ).start()
    }
}
